Deep relation


I’ve got User, RuleViolation and Product (or Service) model. Product or Service is (let me say) a kind of offer. Offer belongs to User. RuleViolation is has offer_id (relation in class returns ActiveQuery) to specific model (Product or Service).

How can I enable sorting over User which added Offer in RuleViolation Grid? In Grid I can add column ‘’ and it displays correct user name but it doesn’t have sorting or filtering.

Thanks for help!

In order to sort by an attribute in a relation, you have to do 2 things in the "search" method of the search model.

  1. Join the related table that has the target attribute of sorting.

public function search($params)


    $query = RuleViolation::find()->joinWith(['offer', 'offer.user']);


Because you need to sort by the name of the user, you have to join ‘user’.

  1. Specify how to sort on the target attribute.


    $dataProvider = new ActiveDataProvider([

        'query' => $query,


        'sort' => [

            'attributes' => [


                // you have to list all the attributes that should be sortable here


                '' => [

                    'asc' => ['' => SORT_ASC],

                    'desc' => ['' => SORT_DESC],





Also check the API doc of ‘Sort’.