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 ‘offer.user.name’ and it displays correct user name but it doesn’t have sorting or filtering.
In order to sort by an attribute in a relation, you have to do 2 things in the "search" method of the search model.
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’.
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
'offer.user.name' => [
'asc' => ['user.name' => SORT_ASC],
'desc' => ['user.name' => SORT_DESC],