【问题标题】:Laravel 5.1 deleting sub-relationship data when row is deletedLaravel 5.1 删除行时删除子关系数据
【发布时间】:2016-04-22 12:49:41
【问题描述】:

我在 Laravel 5.1 中有一个应用程序,其中设置了以下表格;

  • 时间表
  • day_total
  • segment_totals

行属于时间表。 日总数属于时间表。 段总计属于行。

删除时间表时,我还希望它删除 rowday_totalsegment_total 中的行以及 timesheet 表本身中的行。

我在timesheet 模型中设置了以下启动方法;

/**
 * Boot the model.
 *
 */
public static function boot()
{
    parent::boot();

    static::deleting(function($timesheet)
    {
        $timesheet->row()->delete();
        $timesheet->dayTotal()->delete();
    });
}

我在row 模型中设置了以下内容;

/**
 * Boot the model.
 *
 */
public static function boot()
{
    parent::boot();

    static::deleting(function($row)
    {
        $row->day()->delete();
        $row->segmentTotal()->delete();
    });
}

删除时间表时,rowdayTotal 行将被删除,但 daysegmentTotals 不会被删除。如何让 Laravel 触发 row 模型上的删除操作?

【问题讨论】:

  • 能否请您发布您的实体和关系,因为似乎有问题的模型在 MYSQL 中彼此不相关?

标签: php laravel laravel-5 laravel-5.1


【解决方案1】:

当您在关系查询上调用delete() 时,它会对数据库运行直接查询以删除记录。因此,相关模型不会加载,并且无法调用这些模型上的deleting 事件。您需要以可以调用相关模型上的事件的方式删除记录。

您要么需要遍历相关模型并在每个模型实例上调用delete(),要么您可以获取相关id的列表,然后使用destroy()方法(它只是为每个id加载模型并致电delete())。

选项 1:循环遍历相关模型

public static function boot()
{
    parent::boot();

    static::deleting(function($timesheet)
    {
        foreach($timesheet->row()->get() as $row) {
            $row->delete();
        }
        foreach($timesheet->dayTotal()->get() as $dayTotal) {
            $dayTotal->delete();
        }
    });
}

选项 2:使用带有 ID 的 destroy()

public static function boot()
{
    parent::boot();

    static::deleting(function($timesheet)
    {
        // getRelated() method gets the related model from the relationship.
        // This is so you don't have to hardcode \App\Row::destroy()
        // or \App\DayTotal::destroy()

        $ids = $timesheet->row()->lists('id')->all();
        $timesheet->row()->getRelated()->destroy($ids);

        $ids = $timesheet->dayTotal()->lists('id')->all();
        $timesheet->dayTotal()->getRelated()->destroy($ids);
    });
}

【讨论】:

    猜你喜欢
    • 2016-01-02
    • 2020-03-16
    • 2015-10-13
    • 2016-05-01
    • 2015-05-15
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    相关资源
    最近更新 更多