eloquent - average of counts with Laravel 5 -


we have 2 classes: module , resource, module having many resources:

class module extends model {     public function resources() {         return $this->hasmany('app\models\resource');     } }  

and resource belonging module:

class resource extends model {     public function module() {         return $this->belongsto('app\models\module');     } } 

i need show list of modules with:

  1. the number of resources each each module
  2. the average of resources per module

the first 1 added module model can used eager loading:

public function resourcescount() {     return $this->hasmany('app\models\resource')         ->selectraw('module_id, count(*) aggregate')         ->groupby('module_id'); } 

however, can't find efficient , elegant way calculate average of counts calculated resourcescount. know iterate through results of

$modules = module::with('resourcescount')->get();  

and manually, feel there's better out there.

edit: forgot modified accessor resourcescountattribute:

public function getresourcescountattribute() {     if (!$this->relationloaded('resourcescount'))          $this->load('resourcescount');      $related = $this->getrelation('resourcescount');     return ($related) ? (int) $related->aggregate : 0; } 

so can use 'resourcescount' (see response), rather having use 'resourcescount.aggregate'.

the way through iteration or in separate db::select() statement, relying on things group , average().


Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -