【发布时间】: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_ids 和environment_ids。但我收到以下 SQL 错误:
消息:“SQLSTATE[42S22]:未找到列:1054 未知列 '字段列表'中的'role_role_id'(SQL:插入
user_roles_environments(role_role_id,user_user_id) 值 (ROLE_ID, 0))
这里只出现了两个字段。如何添加environment_id?
【问题讨论】: