我一直在做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']);
}
}
下面是我得到的结果:http://imgur.com/ZEph0IB
我希望是这样的:http://imgur.com/nUCQA4Q
发布于 2016-07-11 15:12:37
这里需要的分页详细信息可以在Pagination Helper中获得,而不是分页组件。
因此,我建议您在视图中修改这些数据。
// View/Drones/json/view.ctp
$pagination['has_next_page'] = $this->Paginator->hasNext();
$pagination['has_prev_page'] = $this->Paginator->hasPrev();
$pagination['current_page'] = (int)$this->Paginator->current();
.....
.....
echo json_encode(compact("drone", "pagination"), JSON_PRETTY_PRINT);
发布于 2016-08-25 15:33:50
如果您使用的是CakePHP 3,则可以在请求参数中检索分页器组件生成的分页数据。
在你的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
干杯。
发布于 2019-01-11 20:31:57
使用
$this->request->param('paging')
已弃用。
在CakePHP 3.7中,可以使用以下命令返回分页对象:
current($this->request->getParam('paging'))
https://stackoverflow.com/questions/38300475
复制相似问题