简体   繁体   中英

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?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM