Laravel 4 级联软删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17243637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:00:54  来源:igfitidea点击:

Laravel 4 Cascading Soft Deletes

phpmysqllaravellaravel-4

提问by Half Crazed

Is there a modular way to perform cascading soft deletes in L4?

在 L4 中是否有执行级联软删除的模块化方法?

My database is already designed to do this with hard deletes because all tables are related to another.. however, I'm using soft deletes and really do not want to have to overload the delete()method in my models - simply due to (A) the amount of models, and (B) having to edit the delete()method in all models when other models change.

我的数据库已经设计为使用硬删除来执行此操作,因为所有表都与另一个表相关。但是,我正在使用软删除并且真的不想delete()在我的模型中重载该方法 - 仅仅是因为 (A)模型数量,以及 (B)delete()当其他模型发生变化时,必须在所有模型中编辑方法。

Any pointers or tips would be appreciated.

任何指针或提示将不胜感激。

回答by robjmills

I've got cascading deletes working using model events, for example in a Product model I bind to the deleted event so I can soft-delete all relations:

我已经使用模型事件进行级联删除,例如在我绑定到删除事件的产品模型中,我可以软删除所有关系:

    // Laravel's equivalent to calling the constructor on a model
    public static function boot()
    {
        // make the parent (Eloquent) boot method run
        parent::boot();    

        // cause a soft delete of a product to cascade to children so they are also soft deleted
        static::deleted(function($product)
        {
            $product->images()->delete();
            $product->descriptions()->delete();
            foreach($product->variants as $variant)
            {
                $variant->options()->delete();
                $variant->delete();
            }
        });
    }

回答by Half Crazed

I do know this is possible from within my models:

我知道这在我的模型中是可能的:

public function delete() {
  ChildTable::where('parent_id', $this->id)->delete();
  ChildTable2::where('parent_id', $this->id)->delete();
  parent::delete();
}

But any update to models or table structure would cause this to be appended/edited.. including other models.

但是对模型或表结构的任何更新都会导致附加/编辑......包括其他模型。