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

时间:2017-09-08 15:38:46

标签: rest pagination yii2 api-design

我在yii rest控制器中创建了自己的对象/索引操作,它执行一些简单的操作:

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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

我假设你正在使用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',
];