3 回答
TA贡献1831条经验 获得超9个赞
如果用户和角色之间存在许多关系,则可以按以下方式解决您的问题
这是示例代码User.php
class User extends Authenticatable implements CanResetPassword
{
protected $table = "users";
public function roles(){
return $this->belongsToMany(Role::class,'role_user');
}
}
Role.php
class Role extends Model{
protected $table = "roles";
public function users(){
return $this->belongsToMany(User::class,'role_user');
}
}
在您的控制器上,您可以执行此操作
class AnyTestController extends Controller{
public function test(){
//Suppose your user id is 1 then delete user from pivot table
$user = User::find(1);
$user->roles()->detach();
$user->delete();
}
}
TA贡献1824条经验 获得超5个赞
在删除数据透视表中的用户或角色清除寄存器之前,将此模型添加到模型中。
User.php
protected static function boot ()
{
parent::boot();
static::deleting (function ($user) {
$user->roles()->detach();
});
}
Role.php
protected static function boot ()
{
parent::boot();
static::deleting (function ($role) {
$role->users()->detach();
});
}
- 3 回答
- 0 关注
- 114 浏览
添加回答
举报