我有3个与多对多关系的模型:
模组
public function permissionTypes()
{
return $this->belongsToMany(PermissionType::class, 'permissions')->withPivot('role_id');
}
public function roles()
{
return $this->belongsToMany(Role::class, 'permissions')->withPivot('permission_type_id');
}
角色
public function permissionTypes()
{
return $this->belongsToMany(PermissionType::class, 'permissions')->withPivot('module_id');
}
public function modules()
{
return $this->belongsToMany(Module::class, 'permissions')->withPivot('permission_type_id');
}
PermissionType
public function roles()
{
return $this->belongsToMany(Role::class, 'permissions')->withPivot('module_id');
}
public function modules()
{
return $this->belongsToMany(Module::class, 'permissions')->withPivot('role_id');
}
表格说明:
模组
id
title
status
角色
id
title
权限类型
id
title
数据透视表权限
id
role_id
module_id
permission_type_id
我的同步如下所示:
//array of ids from request to synchronization
$permissions = $request['permissions'];
//role by id from request
$role = Role::findOrFail((int)$roleId);
//module by id from request
$module = Module::findOrFail((int)$moduleId);
//synchronization
$pivotData = array_fill(0, count($permissions), ['role_id' => $role->id]);
$syncData = array_combine($permissions, $pivotData);
$module->permissionTypes()->sync($syncData);
尝试进行同步时出现错误
Connection.php第647行中的QueryException:
SQLSTATE [42000]:语法错误或访问冲突:1066不是唯一的表/别名:“权限”(SQL:选择
permissions
。*,permissions
。role_id
作为pivot_role_id
,permissions
。permission_id
来自pivot_permission_id
上的permissions
内部联接permissions
中的permissions
。id
= permissions
。permission_id
其中permissions
。role_id
= 1)谢谢
最佳答案
恕我直言,您正在尝试设计Laravel中不存在的三对多。解决方案通常是为数据透视表(在您的情况下为permissions
)提供一个用于定义hasManyThrough
关系的模型(在下面的代码中为许可)。
如果我了解您的表结构,我将设计以下关系:
模组
public function permissions()
{
return $this->hasMany(Permission::class);
}
public function roles()
{
return $this->hasManyThrough(Role::class, Permission::class);
}
public function permissionTypes()
{
return $this->hasManyThrough(PermissionType::class, Permission::class);
}
角色
public function permissions()
{
return $this->hasMany(Permission::class);
}
public function permissionTypes()
{
return $this->hasManyThrough(PermissionType::class, Permission::class);
}
public function modules()
{
return $this->hasManyThrough(Module::class, Permission::class);
}
PermissionType
public function permissions()
{
return $this->hasMany(Permission::class);
}
public function modules()
{
return $this->hasManyThrough(Module::class, Permission::class);
}
public function roles()
{
return $this->hasManyThrough(Role::class, Permission::class);
}
允许
public function permissionType()
{
return $this->belongsTo(PermissionType::class);
}
public function role()
{
return $this->belongsTo(Role::class);
}
public function module()
{
return $this->belongsTo(Module::class);
}
告诉我它是否可以为您工作。
关于php - Laravel 5.4中的3个模型多对多同步,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43162104/