问题
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