Laravel 4 Cascading Soft Deletes

对着背影说爱祢 提交于 2019-12-20 14:15:30

问题


Is there a modular way to perform cascading soft deletes in 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.

Any pointers or tips would be appreciated.


回答1:


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();
            }
        });
    }



回答2:


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.



来源:https://stackoverflow.com/questions/17243637/laravel-4-cascading-soft-deletes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!