【发布时间】:2016-11-23 18:12:10
【问题描述】:
最初,我需要从评论表中获取所有产品的平均评分。我已经找到了如何做到这一点的方法,但是当我想访问访问器值时,我被困了几个小时。我想向视图显示聚合的内容,但是我尝试过的每件事都不起作用。请帮忙。
产品型号
protected $table = 'products';
protected $fillable = ['title','body'];
public function scopeActive($query, $default = true){
$query->where('active',$default)->orderBy('created_at','desc');
}
public function productreviews(){
return $this->hasMany(Review::class);
}
public function avgRating(){
return $this->hasOne(Review::class)->selectraw('avg(rating) as aggregate,product_id')->groupBy('product_id');
}
public function getAverageAttribute(){
if (!$this->relationLoaded('avgRating')){
$this->load('avgRating');
}
$relation = $this->getRelation('avgRating');
return ($relation) ? $relation->aggregate : null;
}
审查模型
protected $table = 'reviews';
protected $fillable = ['user_id','body','rating'];
public function product(){
return $this->belongsTo(Product::class);
}
产品控制器
public function show(Product $product){
$getAllProducts = $product->with('avgRating')->active()->get();
return view('products.allproducts',['products'=>$getAllProducts]);
}
显示方法返回的响应
[{"id":1,"title":"Ipsum quos libero iusto.","body":"Ipsum temporibus tenetur voluptates.","active":1,"created_at":"2016-11-23 12:44:02","updated_at":"2016-11-23 12:44:02","avg_rating":{"aggregate":4.5,"product_id":1}},{"id":2,"title":"Ab ducimus quia sed quia pariatur officiis.","body":"Cupiditate aut nihil at est.","active":1,"created_at":"2016-11-23 12:44:02","updated_at":"2016-11-23 12:44:02","avg_rating":{"aggregate":4,"product_id":2}}]
查看
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Products</div>
<div class="panel-body">
@foreach($products as $product)
@if($product->active)
<div class='alert alert-info'>
<h1>{{ $product->title}}</h1>
<p>{{ $product->body }}</p>
<p>{{ $product->avg_rating->aggregate }}</p>
</div>
@endif
@endforeach
</div>
</div>
</div>
</div>
</div>
@endsection
【问题讨论】: