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();
致以敬意,
发布于 2016-07-20 14:59:38
您可以尝试使用以下代码:
$items = Items::where($this->Shop->reviews->avg('rating'),'>',$input)
->get()->toArray();
以获取包含商店数据的商品数据。
$items = Shop::where($this->reviews->avg('rating'),'>',$input)
->with('Item')->get()->toArray();
https://stackoverflow.com/questions/38444037
复制相似问题