Yii2 Rest 中的分页链接 API 自定义操作响应

Pagination Links in Yii2 Rest API Custom Action Response

我在 yii rest 控制器中创建了我自己的 object/index 动作,它做了一些简单的事情:

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": []
    }
]

我想包括此处显示的分页 link 信息,但我不确定如何去做 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 源代码(对我来说)表明 returned 需要实现 yii\data\DataProviderInterface。现在您的代码根本 return 没有处理分页对象。

假设您是 Object extends 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',
];