Yii2 Gridview sort related fields

Is there a functionality in Yii2 how to automatically make sortable all related fields in a GridView? If I use only 1 model, and create an activedataprovider from it, it automatically enables sorting on all fields.

But for every field which comes from a related table, I have to declare it manually, though it is obvious, as is it declared in the relation.

class Customer extends ActiveRecord


        // has fields like name, address, etc

        public function getOrders()


            return $this->hasMany(Order::className(), ['customer_id' => 'id']);




    class Order extends ActiveRecord


        // has fields like id, orderNumber, etc

        public function getCustomer()


            return $this->hasOne(Customer::className(), ['id' => 'customer_id']);



    $dataProvider = new ActiveDataProvider([

        'query' => Order::find(),


    echo GridView::widget([

        'dataProvider' => $dataProvider,

        'columns' => [







This will make the id and the orderNumber sortable by default, as the Order model is the main model on which we searched.

But the customer data, though defined properly in a relation, are not sortable.

To make it sortable I would need to add sth like this:


     $dataProvider->sort->attributes['customer.name'] =  [

                        'asc'=>['customers.name' => SORT_ASC],

                        'desc'=>['cusotmers.name' => SORT_DESC],


     $dataProvider->sort->attributes['customer.address'] =  [

                        'asc'=>['customers.address' => SORT_ASC],

                        'desc'=>['cusotmers.address' => SORT_DESC],


Can’t Yii handle this automatically? If I have more joined tables with a lot of fields and I have to define each sorting manually, I do not see the point in using the relational model and gridview, as it does not help me that much to spare some time…

Oh, yes, and I forgot I also have to make the join manually, otherwise it will not even work:

  $dataProvider = new ActiveDataProvider([

            'query' => Order::find()->joinWith('customer'),


The bad thing here also is, that I use the relation name customer in the joinWith statement, but I have to use the TABLE NAME customers in the sort criteria, otherwise I get an SQL error, as by default Yii does not create an alias for the joined tables.

Renanming relations so that the relation matches the table name is not an option. What if I need to have more relations connected to 1 table, e.g. firstOrder, lastOrder, biggestOrder - I cannot name them just ‘order’. That is why I should be able to use the relation name, not the table in the join. Also as I work with an ORM, I work with objects not tables, and it shouldn’t be needed to know what tables are used and how to make the join - the relation should do the job

Any ideas?