Yii searches and sorts data using correlated models in the GridView. First, we have two models that are directly associated with each other.
?
123456789101112131415 |
ClassAuthorextendsCActiveRecord {...} classPostextendsCActiveRecord {... functionrelations () {returnarray ('author' => array (self: BELONGS_TO, 'author', 'id _ author '),);}...} |
When displaying all the posts in the form of a grid, we want to display the author's name and filter the Post by the keyword in the author's name. The best solution to providing these features (in my opinion) is:
First, you must add a new attribute to the Post model to save the search string (that is, the name of the author to be searched ). you can also use foreign key columns to achieve the same effect, but I do not like this. Save the search string in the search condition instead of the foreign key id. you also need to set the rule for this new attribute to safe in the search condition.
?
123456789101112 |
ClassPostextendsCActiveRecord {public $ author_search ;... publicfunctionrules () {returnarray (... array ('XXX, yyy, author_search ', 'Safe', 'on' => 'Search '),);}} |
Now you can use this attribute in the search condition (standard condition-each model requires a search method. At the same time, we need to use the 'with' attribute of the condition to specify the relationship through which our Post gets the author (this method requires only one database query instead of multiple queries in delayed loading)
?
123456 |
With = array ('author');... $ criteria-> compare ('Author. username', $ this-> author_search, true);...?> |
When we modify the search function, we add a new function to the returned CActiveDataProvider.
?
12345678910111213141516 |
$ Criteria, 'sort => array ('bubuckets' => array ('author _ search' => array ('asc '=> 'Author. username', 'desc' => 'Author. username DESC ',),' * ',);?> |
The attributes of the sorting part in the configuration allows us to overwrite the default value. When we sort by the author_search field, it will sort by the specified rule, and the last * indicates that other fields are sorted by default. In this way, we can also modify the sorting of the default attributes (for example, when you specify to sort by last_name, last_name and first_name should be used in combination ).
So far, we have prepared for our grid display.
?
12345678910111213141516171819 |
Widget ('zii. widgets. grid. CGridView ', array ('dataprovider' => $ model-> search (), 'filter' => $ model, 'columns' => array ('title ', 'Post _ time', array ('name' => 'author _ search', 'value' => '$ data-> author-> username '), array ('class' => 'cbuttoncolumn',);?> |
This is all. we use the username instead of the user ID foreign key column for sorting, and we can use the name keyword to search.