例如,我有三个模型:
Invoice
:有很多卡
Card
:有许多serviceLogs
ServiceLog
class Invoice extends Eloquent {
protected $table = "invoice";
protected $guarded = ["id"];
protected $deleted_at = ['deleted_at'];
use SoftDeletingTrait;
public static function boot() {
parent::boot();
Invoice::deleted(function($invoice) {
if ($invoice->cards()) {
if ($invoice->forceDeleting) {
$invoice->cards()->forceDelete();
} else {
$invoice->cards()->delete();
}
}
});
}
public function cards() {
return $this->hasMany("Card");
}
}
class Card extends Eloquent {
protected $table = "card";
protected $guarded = ["id"];
protected $deleted_at = ['deleted_at'];
use SoftDeletingTrait;
public static function boot() {
parent::boot();
Card::deleted(function($card) {
if ($card->serviceLogs()) {
if ($card->forceDeleting) {
$card->serviceLogs()->forceDelete();
} else {
$card->serviceLogs()->delete();
}
}
});
}
public function serviceLogs() {
return $this->hasMany("ServiceLog");
}
}
class ServiceLog extends Eloquent {
protected $table = "service_log";
protected $guarded = ["id"];
protected $deleted_at = ['deleted_at'];
use SoftDeletingTrait;
}
删除$ invoice时,Invoice模型的boot()函数会自动删除与之关联的所有卡片。
但是从上面的函数中删除了$ card之后没有触发的Card模型的boot()函数。
因此,与每张$卡相关联的所有$ serviceLogs也没有被删除。
我的问题是如何删除Laravel中的递归?
答案 0 :(得分:3)
您需要在每个卡型号上调用delete()
功能。目前你在模型集合上调用它,这并不会导致每个模型的引导方法被调用。
代替:
$forceDeleting = $invoice->forceDeleting;
$invoice->cards->each(function($model) use($forceDeleting){
if ($forceDeleting) {
$model->forceDelete();
} else {
$model->delete();
}
});
同样,如果您的ServiceLog模型也有一个启动方法,您需要在卡::deleted()
启动方法中遵循相同的方法,并迭代每个卡并调用delete()
在每个单独的模型上。