Laravel 4 - Return average score from within model? Laravel 4 - Return average score from within model? sql sql

Laravel 4 - Return average score from within model?


Here are two alternatives for you:

Readability (two queries)

$game = Game::find(1);$game->average = $game->reviews()->avg('score');

Note that this assumes that you have got a reviews function for your relationship in your game model.

public function reviews(){    return $this->belongsTo('Game');}

This alternative is using the avg aggregate function. The aggregate functions provided by the QueryBuilder returns only the aggregate scalar.

Performance (one query)

If you really want to do this in one query. Here is one alternative:

$game = Game::select('games.*', DB::raw('avg(reviews.score) AS average'))    ->join('reviews', 'reviews.game_id', '=', 'game.id')    ->groupBy('reviews.game_id')    ->where('game.id', '=', 1)    ->first();