Yii 2.0: Displaying, Sorting and Filtering Model Relations on a GridView, Gridview with relationships
One of the things you will find tricky to implement is the the sorting and filtering of a GridView's column that displays related model data. As you know if you have been playing with Yii2 lately, there is a new proposed way to search for data and is by using objects that extend from the main entity models and mark the searchable attributes as "safe". So, how do we sort and filter related data on a GridView widget? Lets imagine we have the following relations of a model named "Tour": /* * * @return \yii\db\ActiveQuery */ public function getCountry ( ) { return $this -> hasOne ( Country :: className ( ) , [ ' id ' => ' country_id ' ] ) ; } /* * * @return \yii\db\ActiveQuery */ public function getCity ( ) { return $this -> hasOne ( City :: className ( ) , [ ' id ' => ' city_id ' ] ) ; } And we wish to display the name of the country and the name of the city on a GridView. To do ...