有一个在单个数据库中实现的多租户Laravel应用程序.User
型号中有User
型号和Role
型号,它们之间的关系如下:
public function roles(): BelongsToMany
{
$relation = $this->belongsToMany(Roles::class, 'role_users', 'user_id', 'role_id')->withTimestamps()->withPivot('tenant_id');
$relation = $relation->where(function ($query) {
$query->where('tenant_id', Tenant::current()->id);
});
return $relation;
}
role_users
张桌子里有user_id, role_id, tenant_id
张.一个用户可能存在于多个租户中,当我更新租户中用户的角色时,我只需要更新当前租户的角色,而不是所有租户上的用户角色.以下是我编写的代码:
$user->roles()->syncWithPivotValues($roles, ['tenant_id' => Tenant::current()->id]);
但它不起作用,并且同步所有角色,而不是当前租户的角色.我怎么才能解决这个问题呢?