Laravel count和raw sql count给出了不同的值
在原始sql中运行此查询时:Laravel count和raw sql count给出了不同的值,sql,laravel-5,eloquent,Sql,Laravel 5,Eloquent,在原始sql中运行此查询时: select count(postsid) as total, postsid from posts where postsid = 110 group by postsid total的值为2971(这是正确的),但当尝试通过关系使用Laravel执行此操作时: $item->posts->count('postsid') 返回的值是30934(这是错误的)。我使用的函数是错误的还是其他地方的问题?嗯,在laravel查询中缺少postsid=11
select count(postsid) as total, postsid
from posts
where postsid = 110
group by postsid
total的值为2971(这是正确的),但当尝试通过关系使用Laravel执行此操作时:
$item->posts->count('postsid')
返回的值是30934(这是错误的)。我使用的函数是错误的还是其他地方的问题?嗯,在laravel查询中缺少
postsid=110
它应该是$item->posts->count('postsid',110)
这是因为count(ID)只返回非空记录数的计数。
或
试试下面的方法
$item->posts->distinct('postsid')->count('postsid')
我想你错过了
where
条件和groupby
$item->posts
->select('posts.*', DB::raw('count(postsid) as total, postsid'))
->where('postsid', '=', 110)
->group_by('postsid')
->get();
我从没有在文档中看到第二个论点是可能的,我尝试过,但没有成功。谢谢!这很有效。我试图将它添加到with函数项::with(['posts'=>function($query){//select and where}]),但没有成功