Laravel 4.2 无法在启动时递归工作

Laravel 4.2 not working recursive on boot

比如我有三个模型:

Invoice : 有很多卡片

Card : 有很多服务日志

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() 函数不会触发。

因此与每个 $card 关联的所有 $serviceLogs 也没有被删除。

我的问题是如何删除 Laravel 中的递归?

您需要对每个 Card 模型本身调用 delete() 函数。目前您正在模型集合上调用它,这不会导致调用每个模型的引导方法。

改为:

$forceDeleting = $invoice->forceDeleting;
$invoice->cards->each(function($model) use($forceDeleting){
    if ($forceDeleting) {
        $model->forceDelete();
    } else {
        $model->delete();
    }
});

同样,如果您的 ServiceLog 模型也有一个您想要触发的启动方法,您将需要在 Card ::deleted() 启动方法中遵循相同的方法,并遍历每个 Card 并调用 delete() 在每个单独的模型上。