如何从 HasMany 关系中分离元素?

问题描述 投票:0回答:4

save
关系类上有
saveMany
HasMany
方法,但是
dissociate(Many)
/
detach(Many)
方法在哪里?也没有内置的方法来获取逆关系方法,所以将 id/models 数组与
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
4个回答
2
投票

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

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

0
投票

你可以像这样使用 detach ;

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

传递 ID 数组的位置。

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


0
投票

表演方式(1 db 更新):

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

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

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

0
投票

我是一个老问题,但我带着这个宏来了:

use Illuminate\Database\Eloquent\Relations\HasMany;

HasMany::macro('dissociate', function() {
    $foreignKey = $this->getForeignKeyName();
    $this->each(function($relation) use ($foreignKey) {
        $relation->update([$foreignKey => null]);
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.