如何发送Yii2 RESTful GET请求并将排序指定为参数 [英] How to send Yii2 RESTful GET request and specify sorting as params

查看:518
本文介绍了如何发送Yii2 RESTful GET请求并将排序指定为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将GET请求发送到v1/users端点,在这里我想指定要按priority DESCstatus ASC进行排序的参数.

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.

如您所见,我想发送将映射到SQL WHERE部分的参数:

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

我应该如何在我的HTTP请求中指定要进行这种排序的参数?我认为为了做到这一点,我需要在POST请求中发送JSON数据.但这是一个问题,因为我希望GET请求而不是POST. post/users表示创建用户,而我要get用户.

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.

我想我必须像这样发送JSON对象

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

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

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

首先,在发送GET请求时是否可以发送这样的参数?
其次,如何在PHP中使用cUrl发送这些参数?

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 ?

推荐答案

借助内置的RESTfull API,您可以使用逗号对多属性进行排序,并使用'-'符号进行DESC:

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

GET v1/users?sort=-priority,status

如果使用自定义操作而不是内置一次.确保始终返回数据提供商实例,因此 serializer 可以生成相关的分页和上述参数得到支持:

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(),
]);

这篇关于如何发送Yii2 RESTful GET请求并将排序指定为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆