2016-07-18 24 views
0

Item.php如何返回的所有項目,其中店評論是大於或等於輸入 - Laravel 5.2

class Item extends Model { 

    public function shop() 
    { 
     // belongsTo and not belongsToMany since shops sell used goods, not new goods 

     return $this->belongsTo('App\Shop'); 
    } 
} 

Shop.php

class Shop extend Model { 

     public function reviews() 
     { 
      return $this->hasMany('App\Review'); 
     } 

     public function getRating() 
     { 
      // I could also do $this->reviews->avg('rating'); 

      $reviews = $this->reviews->toArray(); 
      $reviews = array_column($reviews, 'rating'); 
      $reviews = array_sum($reviews); 
      $rating = round(($reviews/$this->reviews->count())); 

      return $rating; 
     } 
} 

我想什麼上述做代碼將返回平均商店評論大於或等於給定輸入的所有商品。例如,如果用戶選擇5星中的3個,則返回平均商店評價爲3或更高的所有商品。我想退回物品,而不是商店。因此,像

$input = request('input'); // ie: 3 
Item::where(*average shop review*, '>=', $input)->get(); 

問候,

回答

0

你可以用下面的代碼試試:

$items = Items::where($this->Shop->reviews->avg('rating'),'>',$input) 
       ->get()->toArray(); 

要與店鋪數據獲取項目的數據。

$items = Shop::where($this->reviews->avg('rating'),'>',$input) 
       ->with('Item')->get()->toArray(); 
+0

我得到一個未定義的屬性錯誤 –

+0

'未定義的屬性:應用程序\ HTTP \控制器\的HomeController :: $ Shop' –

+0

爲其查詢..第一或第二 – jaysingkar

相關問題