CakePHP 3.x Specify a Different Count Query for Pagination

混江龙づ霸主 提交于 2020-04-07 09:26:27

问题


I am trying to customize the pagination query for CakePHP I am using a Model based around a view. The view has some complex calculations in it and when the pagination runs it takes about 3 seconds to pull the 20 rows or so. Then it is running the same view wrapped in a count for the count used in pagination. I can run a simple table count on another table which would cut the load times in half but I am unable to find a simple way to customize a seperate query to run for the counts. Is this even possible?

I know another user asked this question but it was never answered.

Cakephp 3.x Custom Query Pagination

I have tried the way that is used to work in 2.x using a custom paginateCount function in both the entity and the table and neither works I dug through the API a bit but couldn't find anything related to the count specifically.


回答1:


One option would be to use the query builder's counter() method to provide a callback that returns the number of records based on your custom query.

$query->counter(function (\Cake\ORM\Query $query) {
    // assuming $this uses \Cake\ORM\Locator\LocatorAwareTrait
    $OtherTable = $this->getTableLocator()->get('Other');
    $otherQuery = $OtherTable->find();

    // ...

    return $otherQuery->count();
});

The $query argument will be a clone of the query itself. You can either modify that one, or construct a completely new query.

See also

  • Cookbook > Database Access & ORM > Query Builder > Returning the Total Count of Records
  • API > \Cake\ORM\Query::counter()


来源:https://stackoverflow.com/questions/49341033/cakephp-3-x-specify-a-different-count-query-for-pagination

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!