想象我有User
和Role
型号。现在,我正在做的是从数据库中删除几个用户。例如,我删除使用IDS 1、2、3和4的用户。现在,我想从user_id = 1、2、3或4的Pivot表中删除所有内容。我的意思是Laravel实施。
您可以将用户模型上的删除事件挂钩以删除其角色。
user.php
Class User extends Model {
protected static function boot() {
static::deleting(function($model) {
// Whenever we delete a user delete their roles first.
$model->roles()->sync([]);
});
}
function roles() {
return $this->belongsToMany('roles');
}
}
您还可以使用模型事件和观察者来做到这一点,这可能更清洁:https://laravel.com/docs/5.8/eloquent#events。观察者和以上模式的问题是,每当您批处理删除时,您都会有一个n + 1
问题。
如果要批次删除用户最有效的方法是手动删除数据,类似的内容:
function deleteUsers($userIds) {
// Delete the users roles
DB::('user_roles')
->whereIn('user_id', $userIds)
->delete();
// Delete the users
User::whereIn('id', $userIds)
->delete();
}
如果用户和角色与许多关系有很多关系,则只需在下面工作
这是示例代码user.php
class User extends Authenticatable implements CanResetPassword
{
protected $table = "users";
public function roles(){
return $this->belongsToMany(Role::class,'role_user');
}
}
角色.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();
}
}
在模型中添加此Cole之前删除用户或角色清晰寄存器。
user.php
protected static function boot ()
{
parent::boot();
static::deleting (function ($user) {
$user->roles()->detach();
});
}
角色.php
protected static function boot ()
{
parent::boot();
static::deleting (function ($role) {
$role->users()->detach();
});
}