Laravel 删除与static::deleting model的所有关系
我已尝试使用事件处理程序删除关系,但它无法用于删除关系的关系。事件有许多人,人有许多文件Laravel 删除与static::deleting model的所有关系,laravel,eloquent,Laravel,Eloquent,我已尝试使用事件处理程序删除关系,但它无法用于删除关系的关系。事件有许多人,人有许多文件 class Event public static function boot() { parent::boot(); static::deleting(function($model) { // before delete() method call this $model->person()->delete();
class Event
public static function boot() {
parent::boot();
static::deleting(function($model) { // before delete() method call this
$model->person()->delete();
});
}
}
class Person
public static function boot() {
parent::boot();
static::deleting(function($model) { // before delete() method call this
$model->files()->delete();
});
}
}
因此,当我删除事件时,它可以删除person,但不会删除文件行。我该怎么办?您应该逐个调用它,以便在每个模型实例上调用boot方法。因此,获取实例,然后逐个删除它们
class Event
public static function boot() {
parent::boot();
static::deleting(function($model) { // before delete() method call this
foreach($model->person as $person){
$person->delete();
}
});
}
}
所以,我不能像我所说的那样在一行中删除它?不。您可以在迁移中定义删除,就像我所看到的那样
->onDelete('cascade')
。所以它指的是这个警告,对吗?当通过Eloquent发出批量更新或删除查询时,不会为受影响的模型分派已保存、更新、删除和删除的模型事件。这是因为在执行批量更新或删除时,从未实际检索模型
class Person
public static function boot() {
parent::boot();
static::deleting(function($model) { // before delete() method call this
foreach($model->files as $file){
$file->delete();
}
});
}
}