我有一张发票表,它的 struct 如下

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;

}

以下是删除发票的代码

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;

}

发票表上的softDelete工作正常,但其相关记录(付款)仍然存在.如何使用softDelete删除它们?

推荐答案

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

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.

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

This will do the trick:

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

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

Laravel相关问答推荐

到查询构建器的MySQL查询

如何获得每种类型的总和

mysql 加入 ON 和 AND 到 laravel eloquent

Laravel:在失败时处理 findOrFail()

如何更新 Laravel 4 中现有的 Eloquent 关系?

从 Laravel Session 数组中删除项目

Laravel - 加载常见的页眉和页脚以查看

Laravel 5文件夹 struct 中的文件保存在哪里?

静态密码在默认的 Laravel 用户工厂中是如何工作的?

Laravel - 验证 - 如果字段为空则需要

使用 vue-router 更改路由时中止所有 Axios 请求

如何处理 laravel 5 中的私有图像?

为什么客户凭证应该与 Laravel Passport 中的用户相关联?

Laravel Socialite 在本地主机上进行测试,SSL 证书问题?

如果 Laravel 中的值不为空,如何验证输入字段

Laravel 5 - 从控制器级别的所有请求对象中删除参数

登录后 DevTools 无法解析 SourceMap 错误将重定向到该 js 文件

是否可以在 Laravel 的不同数据库中引用外键?

如何在 Laravel 中显示动态复选框的旧数据?

Laravel如何仅响应没有正文消息的204代码状态