Russ Back
Russ Back

Reputation: 923

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

Upvotes: 7

Views: 8215

Answers (1)

Rubens Mariuzzo
Rubens Mariuzzo

Reputation: 29241

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.

Upvotes: 11

Related Questions