How to average multiple columns using Eloquent?

I am looking to get the average of several columns on the corresponding model, something like this:

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

Where communication and friendliness is an array of column names. However, it seems that aggregated functions only support column names, so I do this:

 $attributes = array('communication', 'friendliness'); $score = array(); foreach ($attributes as $attribute) { $score[] = $this->reviews()->avg($attribute); } return round(array_sum($score) / sizeof($attributes), 1); 

This leads to several queries. Any suggestions for best practice here?

thanks

+6
source share
1 answer

To avoid multiple queries, you can use the raw database expression in 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 name of the avg aggregate function is recognized by the entire supported Laravel database, this will not be a big problem.

+9
source

Source: https://habr.com/ru/post/951996/


All Articles