更新具有不同值的多个 Eloquent 模型
Updating multiple Eloquent models with different values
我有一个 Parent
模型与 Child
模型有 hasMany
关系。我想用特定的不同值更新每个 child 中的单个 属性。我该怎么做?
我知道我可以使用批量赋值来更新每个 child 中的 属性 具有相同的值,即
Parent::findOrFail($id)->children()->update(["property"=>"new value"])
但是如何使用单独设置的值来做到这一点?
例如如果我的 Parent 有 4 children 我想用这样的东西设置它
Parent::findOrFail($id)->children()->update(["property"=>[1,2,3,4]])
然后child一个有1,child两个有2等等
这样的事情应该可行,遍历关系集合:
$values = [1, 2, 3, 4];
$parent
->children
->each(fn ($child, $k) => $child->update(["property" => $values[$k] ?? null]));
或者,如果您使用的是不受支持的旧版本 PHP:
$values = [1, 2, 3, 4];
$parent->children->each(function ($child, $k) use ($values) {
$child->update(["property" => $values[$k] ?? null]);
});
我有一个 Parent
模型与 Child
模型有 hasMany
关系。我想用特定的不同值更新每个 child 中的单个 属性。我该怎么做?
我知道我可以使用批量赋值来更新每个 child 中的 属性 具有相同的值,即
Parent::findOrFail($id)->children()->update(["property"=>"new value"])
但是如何使用单独设置的值来做到这一点? 例如如果我的 Parent 有 4 children 我想用这样的东西设置它
Parent::findOrFail($id)->children()->update(["property"=>[1,2,3,4]])
然后child一个有1,child两个有2等等
这样的事情应该可行,遍历关系集合:
$values = [1, 2, 3, 4];
$parent
->children
->each(fn ($child, $k) => $child->update(["property" => $values[$k] ?? null]));
或者,如果您使用的是不受支持的旧版本 PHP:
$values = [1, 2, 3, 4];
$parent->children->each(function ($child, $k) use ($values) {
$child->update(["property" => $values[$k] ?? null]);
});