为什么下面的两个语句表现为differentlY?第一个返回3,第二个返回$progress的1。我认为第一个聚合在数据库上,第二个聚合在服务器上。所以它们应该仍然返回相同的值。
$progress = $this->user->userActivities()->select('date')
->groupBy('date')
->get()->count();
$progress = $this->user->userActivities()->select('date')
->groupBy('date')
->count();
发布于 2017-12-03 00:10:32
->get()->count()
会将雄辩的模型对象加载到内存中,然后对这些对象进行计数。
->count()
将使用DB聚合函数,因此它肯定会更高效:
select count(*) as aggregate ...
发布于 2020-12-20 17:00:09
现在回答已经很晚了,但我也遇到过同样的问题。由于您使用的是groupBy,这两个示例返回两个不同的计数。
$progress = $this->user->userActivities()->select('date')
->groupBy('date')
->get()->count();
这将首先获取行数,然后计算行数并返回计数。
$progress = $this->user->userActivities()->select('date')
->groupBy('date')
->count();
而这将按其在DB中的组对行进行计数,并仅从列表中返回第一组的行记录计数。
对于我的案例,我使用的解决方案不是get()->count(),而是如下
$progress = $this->user->userActivities()
->distinct('date')
->count('date');
发布于 2017-12-02 22:49:14
第一个函数计算返回的记录数,第二个函数计算记录数并返回记录数。例如,如果您使用的分页为10,那么如果计算元素的数量大于10,则第一个分页将产生10,第二个分页将产生实际数量。
https://stackoverflow.com/questions/47608873
复制相似问题