【问题标题】:Laravel insert and update many to many relationships between three tablesLaravel 插入和更新三个表之间的多对多关系
【发布时间】:2020-10-05 17:46:23
【问题描述】:

我的表结构如下:

用户表

user_id
username
password

角色表

role_id
role_name

环境表

environment_id
environment_name

并有一个数据透视表来保持如下关系

User_Roles_Environments 表

user_id
role_id
environment_id

用户可以被分配多个角色,并且可以添加到多个环境中。

我在模型类中添加了以下关系

Environment.php

public function roles() {
    return $this->belongsToMany(
        'App\Models\Role',
        'user_roles_environments'
    )->withPivot('user_id');
}

 public function users(){
     return $this->belongsToMany(
         'App\Models\User',
         'user_roles_environments'
     )->withPivot('role_id');
 }

User.php

public function environments(){
    return $this->belongsToMany(
        'App\Models\Environment',
        'user_roles_environments'
    )->withPivot('role_id');
}

public function roles()
{
    return $this->belongsToMany(
        'App\Models\Role',
        'user_roles_environments'
    )->withPivot('environment_id');
}

Role.php

public function environments() {
    return $this->belongsToMany(
        'App\Models\Environment',
        'user_roles_environments'
    )->withPivot('user_id');
}

public function users() {
    return $this->belongsToMany(
        'App\Models\User',
        'user_roles_environments'
    )->withPivot('environment_id');
}

现在,这是根据表结构定义关系的正确方法吗?当我保存用户时,我给出了相应的role_ids(可以选择多个角色)和environment_ids(可以选择多个环境)。我尝试了以下代码来附加关系。

foreach($request->input('user_roles') as $userRole) {
     $user->roles()->attach($userRole);
 }
 foreach($request->input('user_role_environments') as $userEnvironment) {
     user->environments()->attach($userEnvironment);
 }

其中,输入给出role_idsenvironment_ids。但我收到以下 SQL 错误:

消息:“SQLSTATE[42S22]:未找到列:1054 未知列 '字段列表'中的'role_role_id'(SQL:插入 user_roles_environments (role_role_id, user_user_id) 值 (ROLE_ID, 0))

这里只出现了两个字段。如何添加environment_id

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    所以我假设用户角色的数量与环境的数量相同。 我将计算用户角色的数量并使用该计数来执行 for 循环。在循环中,我可以使用计数作为循环的限制。 这应该可以解决您的问题。

    $user_role_count=count($request->input('user_roles'));
    
    for($i=0;$i<$user_role_count;$i++){
    
    $user->roles()->attach($request->user_roles[$i],['environment_id' => $request->user_role_environments[$i]]);
    }
    

    【讨论】:

      【解决方案2】:

      尝试传递您在表格中可能拥有的自定义列名。

      如下(取自here):

      return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
      

      【讨论】:

        猜你喜欢
        • 2021-05-16
        • 2020-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-24
        相关资源
        最近更新 更多