Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel count和raw sql count给出了不同的值_Sql_Laravel 5_Eloquent - Fatal编程技术网

Laravel count和raw sql count给出了不同的值

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

在原始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=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}]),但没有成功