In the actual development of the YII2.0 project, it is often encountered to use the Yii2.0 self-contained sorting function. The following are the specific ways to use the sort feature.
First, set up sorting rules
Note the introduction of the sort class, such as Useyii\data\sort;
//Set Sort field $sortObject=New Sort([ ' Sort ' =$sort, ' defaultorder ' = [' id ' = ' = Sort_desc], ' attributes ' = [ ' id ' = [ ' ASC ' = [' id ' = ' + sort_asc], ' desc ' = = [' id ' = ' + Sort_desc], ], ' user_name ' = [ ' ASC ' = [' ecs_users.user_name ' = ' + sort_asc], ' desc ' = [' Ecs_users.user_name ' =&G T SORT_DESC], ], ' add_time ' = [ ' ASC ' = [' add_time ' = ' + sort_asc], ' desc ' = [' add_time ' and ' = Sort_desc], ], ], ]);
Second, use the Yii2.0 to bring the paging function and join the sorting
//Working with paging $queryClone=Clone $query; $totalCount=$queryClone-Count(); $pages=NewPagination ([' defaultpagesize ' =$rows, ' totalcount ' =$totalCount, ' pagesizelimit ' =false]); $query=$query->offset ($offset) ->limit ($pages-limit)->orderby ($sortObject-orders)-Asarray ()->all ();
Third, modify the Yii2.0 sort the underlying code
Underlying source: vendor/yiisoft/yii2.0/data/sort.php
1. Add a property to the sort class: public $sort;
2. Add the following code to the source approximately 249 lines: (Implement post to get paging parameters)
// Get request gets the array to be empty, then call the custom property sort. Used to meet post acquisition post-processing custom parameters if(! Isset($params[$this,Sortparam]) { $params[$this $this,sort; }
3. Receive paging parameters in the controller as follows:
$sort $_post Strval ($_post[' sort ']): ' id '; $sort $_post $sort : '-'. $sort;
Note: The ID in Yii2.0 is ordered by ID,-id is ordered in reverse order by ID. This is the reason why the above statement 2 should be handled so.
Use of the YII 2.0 sorting function