Laravel模型删除层次结构

时间:2017-12-11 15:38:04

标签: php laravel eloquent

假设我有3个模型:ParentChildGrandChild。家长hasMany()孩子,孩子hasMany() GrandChild。现在当我->delete()父模型时,Child和GrandChild模型不受影响。但我也想删除相关的模型。我尝试在我的Controller的destroy()方法中执行此操作:

$parent->childs->grandchilds()->delete();
$parent->childs()->delete();
$parent->delete();

但它会抛出BadMethodCallException,方法grandchilds()不存在,即使我在hasMany()模型上设置了Child关系。

如何在不设置外键约束的情况下很好地删除所有相关模型?因为我的应用程序中有超过3个相关模型,此时编辑所有迁移文件将非常耗时。

3 个答案:

答案 0 :(得分:3)

设置foreign key constraints with ->onDelete('cascade'),例如:

$table->foreign('parent_id')->references('id')->on('parents')->onDelete('cascade');

在孙子迁移中也这样做。

在这种情况下,当您删除父模型时,所有相关的子孙将为automatically deleted by DB

答案 1 :(得分:1)

如果由于某种原因你不能按照Alexey的建议实现级联删除,你可以使用循环来完成这个:

foreach($parent->childs AS $child){
  foreach($child->grandchilds AS $grandchild){
    $grandchild->delete();
  }
  $child->delete();
}
$parent->delete();

答案 2 :(得分:0)

您尝试它的方式不起作用,因为您在->grandchilds()->delete()的集合上调用了childs,而不是查询构建器或模型。

一种方法是对孩子们说:

foreach($parent->childs as $child){
    $child->grandchilds()->delete(); // Here you call it on a query builder (relationship)
    $child->delete(); // Here you call it on a model
}
$parent->delete(); // Calling on a model

或者您可以设置https://slack.com/api/chat.postMessage关系并删除(也更高效,因为您只需要3个查询,无论子女数量):

$parent->grandchilds()->delete(); // Assumed the name of hasManyThrough relationship to be "grandchilds"
$parent->childs()->delete();
$parent->delete();
相关问题