How to soft delete related records when soft deleting a parent record in Laravel?

前端 未结 4 595
无人及你
无人及你 2021-02-04 01:36

I have this invoices table that which has the following structure

id | name | amount | deleted_at
2    iMac   1500   | NULL

and a payments tabl

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 02:26

    Eloquent doesn't provide automated deletion of related objects, therefore you'll need to write some code yourself. Luckily, it's pretty simple.

    Eloquent models fire different events in different stages of model's life-cycle like creating, created, deleting, deleted etc. - you can read more about it here: http://laravel.com/docs/5.1/eloquent#events. What you need is a listener that will run when deleted event is fired - this listener should then delete all related objects.

    You can register model listeners in your model's boot() method. The listener should iterate through all payments for the invoice being deleted and should delete them one by one. Bulk delete won't work here as it would execute SQL query directly bypassing model events.

    This will do the trick:

    class MyModel extends Model {
      protected static function boot() {
        parent::boot();
    
        static::deleted(function ($invoice) {
          $invoice->payments()->delete();
        });
      }
    }
    

提交回复
热议问题