[英]Rest api cakephp pagination
我一直在研究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
如果您使用的是 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
干杯。
您在此處需要的分頁詳細信息可在Pagination Helper而不是 Pagination 組件中找到。
因此,我建議您在您的視圖中修改這些數據。
// 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);
使用
$this->request->param('paging')
已棄用。
在 CakePHP 3.7 中,可以使用以下方法返回分頁對象:
current($this->request->getParam('paging'))
在 Cakephp 4.0 中,根據遷移變化,我們必須使用
$paging = $this->request->getAttribute('paging');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.