如何在CakePHP3中为自定义查询添加分页

时间:2016-10-28 21:10:16

标签: pagination cakephp-3.0 finder

这是我的ClientsController:

namespace App\Controller\Api;

use App\Controller\Api\AppController;

class ClientsController extends AppController{
  public $paginate = [
    'page' => 1,
    'limit' => 5,
    'maxLimit' => 15,
    'fields' => [
         'id', 'name', 'user_id', 'dob', 'phone', 'email'
    ],
    'sortWhitelist' => [
        'id', 'name', 'user_id', 'dob', 'phone', 'email'
    ]
 ];




public function index(){
    $clients = $this->Clients->find('clients');
    $this->set([
                'clients'=>$clients,
                '_serialize'=>['clients']
                ]);

   }

}

这是我的自定义Finder(ClientsTable):

 public function findClients(Query $query, array $options){
    $query
          ->select([
                'clients.id', 
                'clients.name'
            ])
            ->where(['clients.user_id =' => 3]);
    return $query;
}

如何为此添加分页?这一切都很有效,它只是缺乏分页。

如果我删除了索引功能,我会得到分页但是我的查找器似乎没有被调用。这就是代码的外观:

namespace App\Controller\Api;

use App\Controller\Api\AppController;

class ClientsController extends AppController{
  public $paginate = [
   'page' => 1,
   'limit' => 5,
   'finder' => 'clients',
   'maxLimit' => 15,
  'fields' => [
     'id', 'name', 'user_id', 'dob', 'phone', 'email'
   ],
  'sortWhitelist' => [
    'id', 'name', 'user_id', 'dob', 'phone', 'email'
  ]
];
}

2 个答案:

答案 0 :(得分:0)

我没有使用" finder"的经验。分页数组上的选项,但您应该只需将查询传递给paginate函数,就可以这样:

$clients = $this->paginate($this->Clients->find('clients'));

答案 1 :(得分:0)

您可以尝试以下代码

$this->loadComponent('Paginator'); /*Load the Paginator component*/
$clients = $this->Paginator->paginate($this->Clients->findClients()); /*Pass your finder method to the Paginator*/

以下是直接使用Paginator组件Using the Paginator Directly

的文档