我一直在研究cakephp。我创建了一个 Api 并配置了路由,但我想在 json 结果中显示分页,但我不能
这是我的代码:
class DronesController extends AppController {
public $paginate = [
'page' => 1,
'limit' => 5,
'maxLimit' => 6,
'fields' => [
'id', 'user_id'
],
'sortWhitelist' => [
'id', 'user_id'
]
];
public function initialize()
{
parent::initialize();
$this->loadComponent('Paginator');
}
public function view($id)
{
$drone = $this->Drones->find()->where(['Drones.user_id' => $id], [
'contain' => ['Accounts', 'Cards', 'Pilotlogs']
]);
$this->set('drone', $this->paginate($drone));
$this->set('_serialize', ['drone']);
}
}
这是我得到的结果:https://i.sstatic.net/obMyn.jpg
我希望它是这样的:https://i.sstatic.net/xDgBw.jpg
最佳答案
如果您使用的是CakePHP 3,您可以在请求参数中检索Paginator组件生成的分页数据。
在您的AppController.php
中,将其放在序列化变量检查之前。
if ($this->request->param('paging') !== false &&
in_array($this->response->type(), ['application/json', 'application/xml'])
) {
$this->set('paging', current($this->request->param('paging')));
}
该函数现在如下所示:
public function beforeRender(Event $event)
{
if ($this->request->param('paging') !== false &&
in_array($this->response->type(), ['application/json', 'application/xml'])
) {
$this->set('paging', current($this->request->param('paging')));
}
if (!array_key_exists('_serialize', $this->viewVars) &&
in_array($this->response->type(), ['application/json', 'application/xml'])
) {
$this->set('_serialize', true);
}
}
if
语句用于检查分页数据是否存在。
$this->request->param('paging') // returns false if it does not exist
您可能会注意到 current()
部分。我用它来去掉型号名称。
如果不使用current()
,结果将是:
"paging": {
"Posts": {
"finder": "all",
"page": 1,
"current": 6,
"count": 6,
"perPage": 10,
"prevPage": false,
"nextPage": false,
"pageCount": 1,
"sort": null,
"direction": false,
"limit": null,
"sortDefault": false,
"directionDefault": false
}
}
使用current()
结果将是:
"paging": {
"finder": "all",
"page": 1,
"current": 6,
"count": 6,
"perPage": 10,
"prevPage": false,
"nextPage": false,
"pageCount": 1,
"sort": null,
"direction": false,
"limit": null,
"sortDefault": false,
"directionDefault": false
}
CakePHP 的 PaginatorHelper
使用此方法来访问分页数据。
来源/引用:Cake\View\Helper\PaginatorHelper
干杯。
关于php - Rest api cakephp 分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38300475/