【问题标题】:Pivot Tables and eloquent Laravel 5.5数据透视表和雄辩的 Laravel 5.5
【发布时间】:2018-05-17 16:49:41
【问题描述】:

这可能是我使用 laravel 以来遇到的最困难的问题,我希望你们中的一些人可以帮助我解决它。

所以,我的数据库中有以下架构:

游戏

id_game

玩家

id_player

Role_Players

id_role 说明

Games_players

role_id game_id player_id

现在,我与游戏和玩家以及以下模型建立了多对多关系

 class Games {

    public function players {

     return $this->belongsToMany(Players::class, Games_players,  id_game, id_player)     


   }
}

这将返回所有与游戏相关的玩家,但是如何返回玩家在此游戏中的角色?我知道我有一个对象 $games->players->pivot,我可以在其中添加列 role_id,但是如何使用 eloquent 获取例如描述?我正在努力完成这项工作。

我将不胜感激。

谢谢。

D

【问题讨论】:

  • 这看起来像是 eloquent 不支持的三元关系。您可能可以参考 many to many 文档小节 Defining Custom Intermediate Table Models 并检查创建自定义数据透视表是否适合您

标签: laravel eloquent


【解决方案1】:

您可以为您的数据透视表创建一个模型,并使用它自己的关系并对其进行处理。因此 Games_players 的模型将与角色、玩家和游戏有关系,反之亦然。

这些关系不必替换您当前的多对多关系,它们可以同时存在。

【讨论】:

    【解决方案2】:

    我有个主意。

    您可以像这样为您的 Players 模型添加关系

    class Players {
    
        public function roles {
    
         return $this->belongsToMany(Roles::class, Games_players,  id_player, id_role )     
    
       }
    }
    

    那么你就可以使用Eager Loading

    $games = Games::with('players.roles')->get()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      • 2020-03-19
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-30
      相关资源
      最近更新 更多