How to query the parent 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 this.
{
"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 would like to query the game according to the total points from all the round. For above example, the total points would be 30 . I am using jenssegers/laravel-mongodb package and would like to know how can I achieve that? Thanks in advance.
For now. I've came up with this.
$games= Game::all();
return $games->each(function ($g) {
$g['total_points'] = $g->rounds->sum('points');
})->filter(function ($g) {
return $g['total_points'] == 30;
})->first();
It is not very clean or optimal. Is there anything that could be improved?
@MichalOravec I've already tried using it. But, laravel-mongodb package throws errors if I use withSum or withCount.
I think you can simply do this:
return $games->first(function ($game) {
return $game->rounds->sum('points') == 30;
});
// Or
return $games->first(function ($game) {
return $game->rounds->sum->points == 30;
});
Please sign in or create an account to participate in this conversation.