Help with sorting in Yii2 gridview. There is a User model, a UserSearch model.

class User extends \yii\db\ActiveRecord { public function rules() { return [ [['email'], 'string', 'max' => 50], [['phone'], 'string', 'max' => 25], [['username', 'password'], 'string', 'max' => 100], ]; } /* считает рейтинг по заполненным полям в таблице и возвращает результат */ public function getRating(){ ... } } class UserSearch extends User { public $rating; public function rules() { return [ ... [['rating'], 'safe'], ]; } public function search($params){...} } 

In gridview, I added the attribute 'rating'.

 GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ 'rating', ], ]); 

It displays the rating, which is considered to be in the getRating () method of the User model. But when I click on 'Rating' in the header of the gridview table, I get the error 'Unknown column' rating '.

Most of the gridview sorting articles describe how to do this sorting by related fields. In my case there is no connection with other tables, there is no rating field in the Users table. Here it just takes place the calculation of the rating of the fields in the User table and the output of the result. How to filter and sort by this column in the gridview table?

    2 answers 2

    If you can transfer the calculation logic of getRating () to the sql query and, accordingly, return it as an add. the field, then everything will start. And with Grid's tools - IMHO only if you do a full sample into an array, calculate-add this field with your hands and feed it all to the grid (there is a data provider for arrays), but the EU option is so-so. You yourself understand that there is no such field in the database, corresponding to it, but it is not in the data provider either, in order to be able to sort / paginate all necessary info should be available at the time of sampling from the database.

      Add the public property $rating to the User model and the corresponding getter: getRating , calculate data in it. UserSearch from UserSearch .

      The property does not have to exist in the database.