Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to average multiple columns using Eloquent?

I'm looking to get the average value across multiple columns on a related model, something like this:

$this->reviews()->avg('communication', 'friendliness')

Where communication and friendliness are an array of column names. However it appears the aggregate functions only support single column names, so I'm doing this:

$attributes = array('communication', 'friendliness');
$score = array();

foreach ($attributes as $attribute)
{
    $score[] = $this->reviews()->avg($attribute);
}

return round(array_sum($score) / sizeof($attributes), 1);

Which results in multiple queries. Any suggestions for a best practice here?

Thanks

like image 793
Russ Back Avatar asked Aug 19 '13 06:08

Russ Back


1 Answers

To avoid multiple queries you can use a raw database expression within Eloquent as shown below:

$averages = $this->reviews()
    ->select(DB::raw('avg(communication) c, avg(friendliness) f'))
    ->first();

echo $averages->c;
echo $averages->f;

Since the aggregate function name avg is recognized by all supported database by Laravel, this will not be a big deal.

like image 152
Rubens Mariuzzo Avatar answered Sep 21 '22 19:09

Rubens Mariuzzo