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:
- the number of resources each each module
- 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
Post a Comment