Laravel雄辩ORM - 删除行和所有内部关系 [英] Laravel Eloquent ORM - Removing rows and all the inner relationships

查看:130
本文介绍了Laravel雄辩ORM - 删除行和所有内部关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三张表, table1 table2 table3 table1 是一对多到 table2 table2 是一对多到 table3

I have three tables, table1, table2, and table3. table1 is one-to-many to table2 and table2 is one-to-many to table3.

我想调用 Table1 :: find($ id):: delete()并拥有所有行从 table2 table3 删除。

I want to invoke Table1::find($id)::delete() and have all the rows from table2 and table3 deleted as well.

我在表中添加了以下内容:

I added the following to my tables:

Table1

public function delete()
{
    $this->table2()->delete();
    return parent::delete();
}

Table2

public function delete()
{
    $this->table3()->delete();
    return parent::delete();
}

但是,我的行来自 table3 不会被删除。如果我从模型 table2 中手动调用删除功能,则表格的行将被删除。我写的代码的方式,不应该 delete()函数从 table2 被调用时$ code> table1 调用它?

However, my rows from table3 are not deleted. Table3's rows get deleted if I manually call the delete function from the model table2. The way I have written the code, shouldn't the delete() function from table2 be called when table1 calls it?

推荐答案

您不能在集合上调用delete() ,既不会在查询构建器上加载远程相关的集合,也可以删除相关的模型,所以您需要的是:

You can't call delete() on the collection, neither load far related collection on the query builder, to remove related models, so what you need is this:

// Table1 model
public function delete()
{
  $this->table2->each(function ($model2) {
    $model2->table3()->delete();
  });

  $this->table2()->delete();
  return parent::delete();
}

这篇关于Laravel雄辩ORM - 删除行和所有内部关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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