我如何获取 laravel 中平均评分的所有数据
How Can i fetch all data with average rating in laravel
我想显示所有产品的平均评分。在这种情况下,我有两个 table,例如 Product Table 和 Product Rating Table
例如:
我的产品table
ProductID | ProductName
-------------------------
1 | ABC Product
2 | XYZ Product
3 | LMN Product
我的评分Table
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();
我没有运行这个查询,但这可能会给你一个问题的想法。
我想显示所有产品的平均评分。在这种情况下,我有两个 table,例如 Product Table 和 Product Rating Table
例如:
我的产品table
ProductID | ProductName
-------------------------
1 | ABC Product
2 | XYZ Product
3 | LMN Product
我的评分Table
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();
我没有运行这个查询,但这可能会给你一个问题的想法。