Divide sum and count result into the same Query?

2

The code below works, but I wanted to know how to do it all right in query , and if the way I'm setting it up is really the best way.

$query = Avaliar::select(DB::raw('COUNT(id) as contar'), DB::raw('SUM(nota) as total'))
        ->where('serie_id', $serie->id)
        ->first();

$nota = $query->total / $query->contar;
    
asked by anonymous 19.12.2017 / 05:14

1 answer

2

You could split it into SQL as follows, for example:

$query = Avaliar::select(DB::raw('(SUM(nota) / COUNT(id)) as nota'))
        ->where('serie_id', $serie->id)
        ->first();

$nota = $query->nota;

Now, yours and this answer come in the same purpose, so, everything will depend on where it will be used, because depending on the rule one of the two do not fit.

19.12.2017 / 13:40