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

问题描述 投票:0回答:3

当我在原始sql中运行此查询时:

select count(postsid) as total, postsid
from posts
where postsid = 110
group by postsid

total的值是2971(这是正确的),但是当试图通过关系尝试使用Laravel:

$item->posts->count('postsid')

返回的值是30934(这是错误的)。我使用的功能是错误的还是其他地方的问题?

sql laravel-5 eloquent
3个回答
1
投票

我想你错过了where条件和group by

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

0
投票

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

它应该是$item->posts->count('postsid',110)


0
投票

这是因为COUNT(ID)仅返回非空记录数的计数。或者尝试以下方法

$item->posts->distinct('postsid')->count('postsid')
© www.soinside.com 2019 - 2024. All rights reserved.