【问题标题】:Laravel model deletion hierarchyLaravel 模型删除层次结构
【发布时间】:2017-12-12 00:15:51
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

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

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

    在孙辈迁移中也这样做。

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

    【讨论】:

    • 虽然这绝对是应该的方式,但提问者明确表示>无需设置外键约束
    • @devk 我错过了那部分。在这种情况下,OP 绝对应该使用您答案中的代码。
    【解决方案2】:

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

    一种方法是对孩子进行 foreach:

    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
    

    或者您可以设置->hasManyThrough(Child, GrandChild) 关系并像这样删除(也更高效,因为您只需要 3 个查询,而不管子节点的数量):

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

    【讨论】:

    • 如果我必须更深一层(或者在以后的某个时间点更深),我该如何设置 hasManyThrough 呢?假设现在我有一个GreatGrandChild 模型,那我该怎么办?
    • 没有on delete cascade 就没有好办法。外键是你最好的朋友。从长远来看,这将节省您的时间并提高性能。
    【解决方案3】:

    如果由于某种原因您无法按照 Alexey 的建议实现级联删除,您可以使用循环来完成此操作:

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

    【讨论】:

      猜你喜欢
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多