如何退回商店评论大于或等于输入的所有项目 - Laravel 5.2

时间:2016-07-18 18:52:56

标签: mysql eloquent laravel-5.2

Item.php

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();

此致

1 个答案:

答案 0 :(得分:0)

您可以尝试使用以下代码:

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

使用商店数据获取商品数据。

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