获得GroupBy Laravel的平均数

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

我正在尝试制作评论系统,我希望在使用group by时得到计数(id)的平均值

如果我使用计数与组合它是有效的,我得到

return $comments  = Comment::select('rating',DB::raw('count(id)  as 
total_reviews'))->where('product_id', $id)->where('shop_name', $shop)-
>groupBy('rating')->get();

结果

  [
{
"rating": 1,
"total_reviews": 1
},
{
"rating": 2,
"total_reviews": 2
},
{
"rating": 3,
"total_reviews": 2
},
{
"rating": 4,
"total_reviews": 6
},
{
"rating": 5,
"total_reviews": 61
}
]

但是当我添加avg()时,我收到一个错误

return $comments = Comment::select('rating',DB::raw('avg(count(id))
as total_reviews'))->where('product_id', $id)->where('shop_name', $shop)-
>groupBy('rating')->get();

一般错误:1111无效使用组功能(SQL:选择rating,avg(count(id))作为来自comments的total_reviews .....

php mysql sql laravel
4个回答
0
投票

Laravel Documentation有一个很好的例子做类似的东西检查这个:

$users = DB::table('users')
                     ->select(DB::raw('count(*) as user_count, status'))
                     ->where('status', '<>', 1)
                     ->groupBy('status')
                     ->get();

使用数据库外观以这种方式尝试并告诉我发生了什么。


0
投票

您试图平均每行的计数,这没有意义。尝试使用subselect:http://sqlfiddle.com/#!9/8f4f8e/4


0
投票

你不能在Mysql中组合聚合函数,你必须使用子查询:Look here


0
投票

我认为不支持嵌套聚合函数。所以,您可以尝试这样的集合平均方法:

$average_rating = Comment::select('rating','product_id','shop_name',
                   DB::raw('count(id) as total_counts'))
                  ->where('product_id', $id)
                  ->where('shop_name', $shop)
                  ->groupBy('rating')
                  ->get()
                  ->avg('total_counts');

在这里,直到get(),你将获得包含每个评级总数的集合,然后avg()将搜索total_counts值并对它们取平均值。

我希望你明白。你可以看到文档https://laravel.com/docs/5.5/collections#method-avg

© www.soinside.com 2019 - 2024. All rights reserved.