【问题标题】:Laravel eloquent relationship between two many to many related tables两个多对多相关表之间的Laravel雄辩关系
【发布时间】:2015-03-07 11:34:45
【问题描述】:

我有很多相关的两个表,“roles”和“users”,数据透视表为“user_roles”。

在角色模型中

$this->belongsToMany('users', 'user_roles');

在用户模型中

$this->belongsToMany('roles', 'user_roles');

这是一个有效的关系吗?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    您想要一个数据透视表和多对多关系,就像您说的那样使用数据透视表。

    Laravel documentation - Eloquent 中解释了您要执行的操作

    【讨论】:

      【解决方案2】:

      没有。第一个参数应该是相关模型的类名:

      $this->belongsToMany('User', 'user_roles');
      
      $this->belongsToMany('Role', 'user_roles');
      

      否则,如果你的外键遵循约定,你应该没问题...

      See the documentation for more info

      【讨论】:

      • 除非您在数据透视表上使用自定义名称,否则您实际上只需要在创建关系时声明您的模型名称。像 $this->belongsToMany('Role');
      • 好吧user_roles 自定义名称。默认为role_user
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 2012-10-08
      • 2016-11-03
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      相关资源
      最近更新 更多