Laravel 4级联软删除

时间:2013-06-21 20:17:20

标签: php mysql laravel laravel-4

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

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

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

2 个答案:

答案 0 :(得分:10)

我使用model events进行级联删除工作,例如在Product模型中我绑定到已删除的事件,因此我可以软删除所有关系:

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

答案 1 :(得分:2)

我知道这可以在我的模型中实现:

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

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

相关问题