[英]How Can i fetch all data with average rating in laravel
我想顯示所有產品的平均評分。 在這種情況下,我有兩個表,如產品表和產品評級表
例如:
我的產品表
ProductID | ProductName
-------------------------
1 | ABC Product
2 | XYZ Product
3 | LMN Product
我的評分表
ID | ProductID | Value
-------------------------
1 | 1 | 4
2 | 1 | 5
3 | 2 | 3
我需要得到這樣的輸出,
[
{
"ProductID": 1,
"ProductName": ABC Product,
"AverageRating": 4.5,
},
{
"ProductID": 2,
"ProductName": XYZ Product,
"AverageRating": 3.0,
},
{
"ProductID": 3,
"ProductName": LMN Product,
"AverageRating": 0,
}
]
如何在 Laravel 中獲得此輸出? 提前致謝!
$data = DB::table('products_table')
->select('products_table.ProductId',
'products_table.ProductName',
\DB::raw('AVG(ratings_table.value) as AverageRating')
->leftJoin('ratings_table', 'ratings_table.ProductId', 'products_table.ProductId')
->groupBy('ratings_table.ProductId')->get();
return $data->toArray();
我還沒有運行過這個查詢,但這可能會讓你對你的問題有所了解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.