1

I want to send GET request to v1/users endpoint, where as params I want to specify that I want to do ordering by priority DESC and status ASC.

As you can see I want to send params that will map to SQL WHERE parts:

SELECT * FROM table WHERE something ORDER BY priority DESC, status ASC

How I am supposed to specify as params in my HTTP request that I want this sorting ? I think that in order to do this I need to send JSON data in POST request. But that is a problem, because I want GET request not POST. post/users means create user, and I want to get users.

I guess that I would have to send JSON object like this

"sort":[ {"priority":"DESC", "status":"ASC"} ]

First, is it possible to send params like this when you send GET request ?
Second, how would you send these params using cUrl in PHP ?

black-room-boy
  • 659
  • 2
  • 11
  • 23

1 Answers1

3

with the built-in RESTfull API you can use comma for multi attributes sorting and '-' sign for DESC:

GET v1/users?sort=-priority,status

If using a custom action instead of the built-in onces. be sure to always return a data provider instance so the serializer can generate related pagination and the above params get suppoted:

// instead of: return $modelClass::find()->all();
return new ActiveDataProvider([
    'query' => $modelClass::find(),
]);
Salem Ouerdani
  • 7,596
  • 3
  • 40
  • 52
  • Do you maybe know how can I sort by related table column ? I have profile filed that is profile relation with profile table. `public function fields() { $fields = parent::fields(); $fields[] = 'profile'; return $fields; }` . So I would like to sort by profile.created_at. Do you know how ? – black-room-boy Apr 07 '16 at 10:39
  • In this case I think you'll need to override `$actions['index']['prepareDataProvider']` and add sort to the custom `ActiveDataProvider` instance via `$dataProvider->sort->attributes['profile'] = [..]` before returning it like it is done in [this example](http://www.ramirezcobos.com/2014/04/16/displaying-sorting-and-filtering-model-relations-on-a-gridview-yii2/). – Salem Ouerdani Apr 07 '16 at 12:20
  • I personally use the Search Class. it is where I do filtering and sorting. this is one more [example](http://webtips.krajee.com/filter-sort-calculated-related-fields-gridview-yii-2-0/) on how to cutomize the searchClass. and this is [how I use it in REST](http://stackoverflow.com/questions/25522462/yii2-rest-query/30560912#30560912) – Salem Ouerdani Apr 07 '16 at 12:28
  • I have asked full new question here: http://stackoverflow.com/questions/36474282/how-to-sort-by-related-table-field-when-sending-yii2-rest-get-request – black-room-boy Apr 07 '16 at 12:37