Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting data in default rest api - Yii2 framework

Tags:

yii2

I setup the default rest api in yii2 and it gives me the list of users when I run "api/web/v1/users" using get method.

Is there any way to sort the output data like "api/web/v1/users?sort=name desc" ?

like image 761
Mohd Shahid Avatar asked Nov 12 '14 10:11

Mohd Shahid


1 Answers

There is no need to write code for it. Yii already supports inverse sorting by adding a negative sign to attribute name as shown here [Yii core code].

Unless name is not included in your model's safe attributes list, you can just use sort=-name instead of sort=name desc :

api/web/v1/users?sort=-name
  • Note: you can also chain sorting within commas : api/web/v1/users?sort=-name,id,-date

Otherwise if your field is not a safe attribute or when advanced sorting is needed, then you'll have to override IndexAction::prepareDataProvider or configure it to return an activeDataProvider which specifies how your sorting should work.

like image 148
Salem Ouerdani Avatar answered Sep 30 '22 00:09

Salem Ouerdani