doufei2194 2019-04-01 13:41
浏览 56

如何通过嵌套关系来加载多个关系和组

In a sports app, I want to display a list of teams and the players in each team, and have the players grouped by their position.

Here's how the model relationships are defined.

Each Position is linked to a Sport. In Football you'd have CF, ST, GK, etc. In Basketball you'd have PG, PF, C, etc.

class Sport {

  public function positions()
  {
    return $this->hasMany(\App\Position::class);
  }

}

The Position class knows about every Player that plays the Position.

class Position {

  public function sport()
  {
    return $this->belongsTo(\App\Sport::class);
  }

  public function players()
  {
    return $this->hasMany(\App\Player::class);
  }

}

Each Player can play a specific Position on a single Team.

class Player {

  public function position()
  {
    return $this->belongsTo(\App\Position::class);
  }

  public function team()
  {
    return $this->belongsTo(\App\Team::class);
  }

}

And each Team is directly related to a Sport and each Player can play a Position on that Team.

class Team {

  public function sport()
  {
    return $this->belongsTo(\App\Sport::class);
  }

  public function players()
  {
    return $this->hasMany(\App\Player::class);
  }

}

Now, here's my issue. I want to return a list of teams, with the positions being played on each team, and the players playing each position on that team. My desired response would look something like this.

{
  "teams": [
    {
      "id": 1,
      "name": "Barcelona",
      "positions": [
        {
          "id": 1,
          "name": "Center Forward",
          "players": [
            {
              "id": 1,
              "name": "Lionel Messi"
            }
          ]
        }
      ]
    }
  ]
}

I've tried a variety of approaches but I can't seem to get it right. The code below ends up giving me an acceptable structure, but the players aren't filtered by team, so I get all the players that play the position, regardless of the team. By example, the Goalkeeper position would contain keepers from all teams which is definitely wrong.

Team::with(['sport.positions.players'])->paginate();

I feel like it might be something like this.

Team::with(['players.position' => function ($query) { /* insert groupBy magic */ }])->paginate();

Any ideas?

  • 写回答

3条回答 默认 最新

  • dongzheng3113 2019-04-01 14:55
    关注

    You should get your teams then load other data to it:

    $teams->load('sport.positions.players');
    

    Note: use paginate count in your paginate function as a parameter like this:

    $teams->load('sport.positions.players')->paginate(5);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测