Laravel计数和原始SQL计数给出不同的值

时间:2018-09-17 10:06:35

标签: 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(这是错误的)。我使用该功能是否错误,还是其他地方存在问题?

3 个答案:

答案 0 :(得分:1)

我认为您错过了where条件和group by

$item->posts
    ->select('posts.*', DB::raw('count(postsid) as total, postsid'))
    ->where('postsid', '=', 110)
    ->group_by('postsid')
    ->get();

答案 1 :(得分:0)

好吧,您在laravel查询中缺少postsid = 110

应为$item->posts->count('postsid',110)

答案 2 :(得分:0)

这是因为COUNT(ID)仅返回非空记录数的计数。 要么 尝试以下

$item->posts->distinct('postsid')->count('postsid')
相关问题