2017-09-08 90 views
1

Laravel平均檢討,我有2個表:產品編號

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) 

如何互聯數據庫並顯示每個產品在索引上的平均評分?我在這裏發現了一些解決方案,但我無法使其工作。
P.S:插入Review表中的所有內容都是正確的,我只需要爲每個產品顯示它。先謝謝你!

+0

展示你的工作.. – Devon

+0

應該是這樣的產品 - > reviews-> AVG( '評級') – twothreebrent

+0

@twothreebrent我得到「嘗試獲取非對象的屬性' – Hades2x

回答

1

沒有雄辯,它會是這樣的,你可以確保它輸出的東西?

$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; 
+0

它適用於您的Eloquent版本。許多! – Hades2x

+0

不客氣:) – Sletheren