我的桌子看起来像这样。
id | restaurant_id | user_id | rating | comment
1 1 2 3.5 comment1
2 1 2 2.1 comment2
3 1 2 4.1 comment3
4 1 2 1.6 comment4
现在,我的restaurant_id为1.我想要的是获得最高评分(4.1),最低评分(1.6)和平均评分(无论如何)。我正确地做到了,但我也想发表评论。像这样的东西:
{
"data": [
max:{
max_rating:4.1,
comment:"comment 3",
id: 3
},
min:{
min_rating:1.6,
comment: "comment 4",
id: 4,
}
avg:{
avg_rating:"whatever it is",
//this won't have comment and id at all.
}
]
}
我尝试过:
$data = \App\Http\Models\Review::select("id", "comment",DB::raw("MAX(rating) AS max_price, MIN(rating) AS min_price"))
->where("restaurant_id", 1)
->groupBy("id")
->get();
但是不能按照我的解释工作。
答案 0 :(得分:1)
更直接的解决方案是执行3个单独的查询:
$avg = Review::select(DB::raw('avg(rating) as avg_rating')
->where('restaurant_id', 1)
->groupBy('restaurant_id')
->get();
$max = Review::select('id','comment','rating')
->where('restaurant_id', 1)
->orderBy('rating','DESC')
->first();
$min = Review::select('id','comment','rating')
->where('restaurant_id', 1)
->orderBy('rating','ASC')
->first();
$json = json_encode(['data' => [
'avg' => $avg,
'max' => $max,
'min' => $min
]]);
您可以通过一次查询提取最大值,最小值和平均值,但不包括id和最大值/最小值的注释:
$stats = Review::select(DB::raw('avg(rating) as avg_rating, max(rating) as max_rating, min(rating) as min_rating')
->where('restaurant_id', 1)
->groupBy('restaurant_id')
->get();
答案 1 :(得分:1)
一种在Laravel中获取最小值,最大值和平均值的简单方法
$stats=stats::where('userid',Auth::User()->id)->get();
$min=$stats->min('point');
$max=$stats->max('point');
$avg=$stats->avg('point');
答案 2 :(得分:0)
我会尝试这些:
$average = \App\Http\Models\Review::where("restaurant_id", 1)->avg('rating');
$max = \App\Http\Models\Review::where("restaurant_id", 1)->max('rating');
$min = \App\Http\Models\Review::where("restaurant_id", 1)->min('rating');
如果您需要同时为许多餐馆计算这些值,那么在您的消息中编写的查询将是一个不错的开始。它给您带来什么结果而不是预期的价值?