我有一个问题,那就是如何制定一个我无法访问的查询。当做像这样的事情时
$model->where('something')
->distinct()
->paginate();eloquent运行一个查询来获取总计数,该查询如下所示
select count(*) as aggregate from .....问题是,如果在查询中使用distinct,则需要类似于
select count(distinct id) as aggregate from .....才能得到正确的总数。然而,Eloquent并没有这样做,因此返回了错误的总数。获取distinct in计数的唯一方法是通过查询构建器传递一个参数,例如->count('id'),在这种情况下,它将添加该参数。问题是这个查询是自动生成的,我无法控制它。
有没有办法诱使它在count查询中添加distinct?
P.S深入研究构建器代码,我们发现一个IF语句请求count()方法上的一个字段,以便将distinct属性添加到计数中。Illuminate\Database\Query\Grammars\BaseGrammar@compileAggregate
if ($query->distinct && $column !== '*')
{
$column = 'distinct '.$column;
}
return 'select '.$aggregate['function'].'('.$column.') as aggregate';P.S.1我知道在SQL中你可以做一个group by,但由于我渴望加载东西,这不是一个好主意,因为它会在每个其他查询中添加一个in (找到的id的数量),这会显着减慢速度。
发布于 2017-03-14 02:06:05
我遇到了完全相同的问题,并找到了两个解决方案:
不好的:
$results = $model->groupBy('foo.id')->paginate();它可以工作,但如果您有大量的行数(这是我的情况),那么它将消耗太多的内存(和时间)。
更好的:
$ids = $model->distinct()->pluck('foo.id');
$results = $query = $model->whereIn('foo.id', $ids)->paginate();我试了一下,结果是100k,一点问题都没有。
https://stackoverflow.com/questions/23689601
复制相似问题