2016-11-23 32 views
1

最初,我需要從所有產品的評論表中獲得平均評分。我已經建立了如何做到這一點的方式,但是當我想要訪問訪問器值時,我陷入了數小時的困境。我想向觀衆展示聚合的內容,但是我試過的每一件事,都沒有成功。請幫忙。laravel 5.3通過訪問器加載關係後無法訪問屬性

產品型號

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

的ProductsController

public function show(Product $product){ 
    $getAllProducts = $product->with('avgRating')->active()->get(); 
    return view('products.allproducts',['products'=>$getAllProducts]); 

}

從表演方法返回的響應210
[{"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 

回答

0

該解決方案是編寫函數是這樣的:

public function avgRating() { 
    return $this->productreviews()->avg('rating'); 
} 
+0

這個這麼想的幫助。它顯示此錯誤:Builder.php中的FatalThrowableError第674行: 調用成員函數addEagerConstraints()on float –

+0

您是否嘗試過沒有括號?像這樣: $ this-> productreviews-> avg('rating') –

+0

是的,結果相同。 –