CakePHP 3.x为分页指定不同的计数查询 [英] CakePHP 3.x Specify a Different Count Query for Pagination
问题描述
我正在尝试为CakePHP自定义分页查询,我正在使用基于视图的模型。视图中包含一些复杂的计算,当分页运行时,大约需要3秒钟才能拉出20行左右。然后,它运行包含在用于分页计数的计数中的相同视图。我可以在另一个表上运行一个简单的表计数,这样可以将加载时间减少一半,但是我找不到一种简单的方法来定制一个单独的查询来运行该计数。
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.
我尝试了在实体和表中使用自定义的 paginateCount 函数在2.x中使用的方式,但我都没有通过API稍作挖掘但无法使用
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.
推荐答案
一种选择是使用查询生成器的计数器()
方法,以提供一个基于您的自定义查询返回记录数的回调。
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();
});
$ query
参数将是一个克隆查询本身。您可以修改该查询,也可以构建一个全新的查询。
The $query
argument will be a clone of the query itself. You can either modify that one, or construct a completely new query.
另请参见
- Cookbook > Database Access & ORM > Query Builder > Returning the Total Count of Records
- API > \Cake\ORM\Query::counter()
这篇关于CakePHP 3.x为分页指定不同的计数查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!