php - Count products and reviews of a brand using eloquent relationhips -


i have 3 models:

class brand extends \eloquent { protected $fillable = [];  public function product() {     return $this->hasmany('product'); } }    class product extends \eloquent {  protected $fillable = [];  public function reviews() {     return $this->hasmany('review'); }     public function brand() {     return $this->belongsto('brand'); }  }  class review extends \eloquent { protected $fillable = [];  public function product() {     return $this->belongsto('product'); }     } 

i'm trying display brand names along product , review counts in view:

{{ $brand->product->count() }}  

it works this, doesn't display reviews count:

{{ $brand->product->reviews->count() }} 

neither for:

{{ $brand->product->reviews->count() }} 

errors i'm getting are:

errorexception (e_unknown)  undefined property: illuminate\database\eloquent\collection::$review  errorexception (e_unknown)  undefined property: illuminate\database\eloquent\collection::$reviews 

the problem can't call relation on collection of model on model itself. means have loop on products , count reviews of each 1 of them.

basically that

$counter = 0; foreach($brand->product $product){     $counter += $product->reviews()->count(); } echo $counter.' reviews!'; 

now bad on database performance. first queries products , each product makes request db. can use eager loading avoid this.

$counter = 0; $products = $brand->product()->with('reviews')->get(); foreach($products $product){     $counter += $product->reviews()->count(); } echo $counter.' reviews!'; 

with eager loading loads data 1 query , in memory when $product->reviews()

to finish things off here can put in function in brand model

public function getproductreviewcount(){     $counter = 0;     $products = $this->product()->with('reviews')->get();     foreach($products $product){         $counter += $product->reviews()->count();     }     return $counter; }  {{ $brand->getproductreviewcount() }} 

sidenote: suggest change name of relationship product products. makes more sense , convention use plural.


Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -