【问题标题】:How to dissociate elements from a HasMany relation?如何从 HasMany 关系中分离元素?
【发布时间】:2022-02-15 00:39:01
【问题描述】:

HasMany 关系类上有 save 和 saveMany 方法,但 dissociate(Many)/detach(Many) 方法在哪里?也没有内置的方法来获取反向关系方法,那么将 id/模型数组与 HasMany 关系对象分离的最佳方法是什么。

目前我正在使用:

$hasMany = $parent->theRelationship(); // Get the relationship object.
$child = $hasMany->getRelated(); // Get an empty related model.
$key = $hasMany->getForeignKeyName(); // Get the name of the column on the child to set to NULL.
$child->findMany($IDs)->each(function($model) use ($key) {
  $model->$key = NULL;
  $model->save();
});

这可能会更短,例如:

$hasMany = $parent->theRelationship();
$hasMany->dissociate($IDs);

如果您从 Taylor 那里得到任何关于他为什么没有实现此功能的官方回答,我会在 GitHub 上看到他关闭此类功能请求。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    我不确定为什么没有函数,但为了比您的示例更高效,您可以使用 DB 类,例如:

    \DB::table('child_table')->where('parent_id', $parent->id)->update(['parent_id' => null]);
    

    【讨论】:

    • 好的,这用更有效的方式替换了findMany 语句,对吧?要检索列的名称 parent_id 和子表的名称,我仍然需要通过我的 sn-p 的其余部分。
    • 请注意,OP 想要使用一组特定的子资源而不是全部,而且他事先不知道外部表和列名,所以这会更合适:$key = $parent->theRelationship()->getForeignKeyName(); \DB::table($parent->theRelationship()->getModel()->getTable())->where($key, $parent->id)->whereIn('id', $IDs)->update([$key => null]);
    【解决方案2】:

    执行方式(1 db 更新):

    $partent->theRelationship()->update(['parent_id' => null]);
    

    可读方式(多个数据库更新):

    $parent->theRelationship->each->parentRelationship()->dissociate();
    

    【讨论】:

      【解决方案3】:

      你可以像这样使用分离;

      $parent->theRelationship()->detach([1,2,3])
      

      在哪里传递一个 ID 数组。

      来自 Laravel 文档: "为方便起见,附加和分离也接受 ID 数组作为输入"

      【讨论】:

      • 这不只是BelongsToMany关系吗? HasMany 上不存在分离,或者是吗?我在 API 参考中没有看到它
      • 对,detach() 方法仅适用于BelongsToMany。它是InteractsWithPivotTable 的一部分,顾名思义,它不用于简单的外键关系。
      猜你喜欢
      • 2019-10-02
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 2015-11-29
      • 1970-01-01
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      相关资源
      最近更新 更多