Php 按产品id列出的Laravel平均审查

Php 按产品id列出的Laravel平均审查,php,laravel,Php,Laravel,所以我有两张桌子: 1. Products - id, title, description, price, category 2. Reviews with id, user_id, rating, product_id 我想开一家商店。因此,在每个产品页面中,我都有一个表单,用户可以在其中提交评论,给出1-5颗星。在索引页面上,所有产品都显示有标题、说明、类别、价格,我想显示每个产品的平均评级。我已经设置了如下关系: Products -> hasMany(review) Revie

所以我有两张桌子:

1. Products - id, title, description, price, category
2. Reviews with id, user_id, rating, product_id
我想开一家商店。因此,在每个产品页面中,我都有一个表单,用户可以在其中提交评论,给出1-5颗星。在索引页面上,所有产品都显示有标题、说明、类别、价格,我想显示每个产品的平均评级。我已经设置了如下关系:

Products -> hasMany(review)
Review -> belongsTo(user)
Review -> belongsTo(product)
User -> hasMany(review)
如何对数据库进行互操作,并在索引上显示每个产品的平均评级?我在这附近找到了一些解决方案,但我无法使其发挥作用。

附言:每次插入评审表都是正确的,我只需要为每个产品显示它。提前谢谢你

如果没有雄辩,它会是这样的,你能确保它输出一些东西吗

$reviews = Product::find($id)->reviews;
$avg = 0;
foreach($reviews as $rev){
 $avg += $rev->rating;
}
return round($avg/count($reviews));
有了雄辩,它会像:

$product = Product::find($id);
$avg = $product->reviews()->avg('rating');
return $avg;

显示您的工作..应该类似于Product->reviews->avg('rating')@twothreebrent我得到“尝试获取非对象的属性”产品->评论的输出是什么?如果为空,则关系中是否存在问题,或者没有针对该特定关系设置任何评论product@Sletheren它返回整个表内容
[{“id”:2,“创建时间”:“2017-09-07 12:22:07”,“更新时间”:“2017-09-07…等”
它与您雄辩的版本配合使用。非常感谢!