Saz
Saz

Reputation: 1

In Laravel, how to query the parent model according to the the sum of child fields?

I have two models, Game and Round. A game has many rounds, and a round belongs to a game. The structure is something like the following.

{
  "game":{
    "title": "Game One",
    "description": "A game one",
    "rounds": [
      {
        "title": "Round 1",
        "points": 10
      },
     {
        "title": "Round 2",
        "points": 10
      },
      {
        "title": "Round 3",
        "points": 10
      }
    ]
  }
}

I want to query the game according to the total points from all the rounds. So for the above example, the total points would be 30. I am using the jenssegers/laravel-mongodb package and would like to know how I can achieve that?

Upvotes: 0

Views: 537

Answers (1)

Emaad Infotech
Emaad Infotech

Reputation: 121

please try the below code:

Please first add the below code in the Game modal for the relationship with the Round modal

public function round() {
    return $this->hasMany(Round::class,'game_id','id');
}

Then add below function in your controller

public function getGame()
{
    return Game::with('round')
    ->select("games.*",DB::raw("sum(rounds.points) as total_point"))
    ->groupBy('games.id')
    ->leftJoin('rounds','rounds.game_id','=','games.id')
    ->get();
}

Upvotes: 1

Related Questions