在Laravel中,如何根据儿童领域的总和来查询父模型?

发布于 2025-01-23 06:18:22 字数 556 浏览 0 评论 0原文

我有两个型号,game圆形。游戏有很多回合,一轮属于游戏。该结构如下所示。

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

我想根据所有回合的总点查询游戏。因此,在上面的示例中,总点将为 30 。我正在使用Jenssegers/Laravel-Mongodb软件包,并想知道如何实现这一目标?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╰◇生如夏花灿烂 2025-01-30 06:18:22

请尝试以下代码:

请先在 game 模式中添加以下代码,以使其与 round 模态的关系

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

,然后在控制器中添加以下功能

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

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文