软删除Laravel中的父记录时如何软删除相关记录? [英] How to soft delete related records when soft deleting a parent record in Laravel?

查看:289
本文介绍了软删除Laravel中的父记录时如何软删除相关记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个发票表具有以下结构

  id |名称|金额| deleted_at 
2 iMac 1500 | NULL

和具有以下结构的付款表

  id | invoice_id |金额| deleted_at 
2 2 1000 | NULL

发票模型

  class Invoice extends Model {

use SoftDeletes;

}

这里是删除发票的代码

  public function cancel(Request $ request,$ id)
{
$ record = Invoice :: findOrFail($ id) ;
$ record-> delete();
return response() - > json([
'success'=>'OK',
]);
}

付款模式

  class Payment extends Model {

use SoftDeletes;

}

发票表中的softDelete完美但其相关记录(付款)仍然存在。如何使用softDelete删除?

解决方案

口述不提供自动删除相关对象,因此您需要自己编写一些代码。幸运的是,这很简单。



雄辩的模特在模式生命周期的不同阶段发起不同的事件 - 您可以在这里阅读更多: http://laravel.com/docs/5.1/eloquent#events 。您需要的是一个侦听器,当删除事件被触发时,该侦听器将会运行 - 此侦听器应该删除所有相关对象。



您可以注册模型您的模型的 boot()方法中的侦听器。听众应该遍历所有正在删除的发票的付款,并逐个删除。批量删除不会在这里工作,因为它将直接绕过模型事件执行SQL查询。



这将会诀窍:



pre> class MyModel extends Model {
protected static function boot(){
parent :: boot();

static :: deleted(function($ invoice){
$ invoice->付款() - > delete();
});
}
}


I have this invoices table that which has the following structure

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

and a payments table with the following structure

id | invoice_id | amount | deleted_at
2    2            1000   | NULL

Invoice Model

class Invoice extends Model {

    use SoftDeletes;

}

here's the code to delete the invoice

public function cance(Request $request,$id)
{
    $record = Invoice::findOrFail($id);
    $record->delete();
    return response()->json([
        'success' => 'OK',
    ]);
}

Payments model

class Payment extends Model {

    use SoftDeletes;

}

The softDelete on Invoice table works perfectly but its related records (payments) still exists.How do I delete them using softDelete?

解决方案

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 mode's lifecycle - 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();
    });
  }
}

这篇关于软删除Laravel中的父记录时如何软删除相关记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆