我在 yii Rest Controller 中创建了自己的对象/索引操作,它做了一些简单的事情:
public function actionIndex($name){
$query = Object::find();
$count = $query->count();
$pagination = new Pagination(['totalCount'=>$count]);
$objectList = $query->offset($pagination->offset)->limit($pagination->limit)->all();
return $objectList;
}
当我向 http://localhost:8443/v0/objects?name=warehouse&page=1&per-page=1 发出请求时,我收到以下响应:
[
{
"id": 2,
"data": {
"city": "Test",
"name": "ABC Warehouse",
"postal_code": "M1F 4F2",
"street_address": "1234 Street",
"owner": 76,
"created_at": "2016-09-23 15:10:20",
"updated_at": "2017-07-27 11:56:15",
"created_by": 9,
"updated_by": 13
},
"displayData": []
}
]
我想包含此处所示的分页链接信息,但不知道如何进行此操作 http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html
HTTP/1.1 200 OK
...
X-Pagination-Total-Count: 1000
X-Pagination-Page-Count: 50
X-Pagination-Current-Page: 1
X-Pagination-Per-Page: 20
Link: <http://localhost/users?page=1>; rel=self,
<http://localhost/users?page=2>; rel=next,
<http://localhost/users?page=50>; rel=last
最佳答案
我假设您正在使用 yii\rest\ActiveController
快速浏览 yii2 源代码表明(对我来说)无论返回什么都需要实现 yii\data\DataProviderInterface。现在,您的代码根本不返回要处理的 Pagination 对象。
假设您的对象扩展了 ActiveRecord,请在您的操作中尝试此操作...
public function actionIndex($name){
$query = Object::find(); // Assumes Object extends ActiveRecord
$countQuery = clone $query; // Good idea to clone query
$count = $countQuery->count();
$pagination = new Pagination(['totalCount'=>$count]);
$query->offset($pagination->offset)->limit($pagination->limit);
return new ActiveDataProvider([
'query' => $query,
'pagination' => $pagination,
]);
}
请注意,此代码未经测试。希望无论如何都会有帮助。
--- 编辑 ---
还在 yii\rest\ActiveController 中设置此属性(按照 Scott 的建议)
public $serializer = [
'class' => 'yii\rest\Serializer',
'collectionEnvelope' => 'items',
];
关于rest - Yii2 Rest API 自定义操作响应中的分页链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46120058/