php - 获取 Laravel GroupBy 的平均计数

标签 php mysql sql laravel

我正在尝试制作评论系统,我想在使用分组依据时获得计数(id)的平均值

如果我将 count 与 group by 结合使用,它会起作用并且我得到

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();

General error: 1111 Invalid use of group function (SQL: select rating, avg(count(id)) as total_reviews from comments.....

最佳答案

Laravel Documentation 中有一个很好的例子它做了类似的事情,检查一下:

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

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

关于php - 获取 Laravel GroupBy 的平均计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47924648/

相关文章:

php - 如何在 PHP/MYSQL 中获取 DISTINCT ID 值?

PHP 多个客户端访问同一文件

php - 图片上传集成到注册页面

java - 无法创建数据库jdbc

java - 如何检查结果集是否为空

java - 如何在Hibernate中定义非生成的主键字段

php - 谷歌可视化 AreaChart 在 IE7 中给出 "Invalid Argument"

mysql - unix_timestamp 未返回预期输出

android - Android Studio 实时从Mysql数据库获取数据

sql - 尝试连接表并按一个不同的最大值进行选择