gpt4 book ai didi

php - laravel - 更新与许多 'childs' 的关系

转载 作者:搜寻专家 更新时间:2023-10-31 21:21:09 25 4
gpt4 key购买 nike

我有这个数据库:
parent

| id |  name  |  
+----+--------+
| 1 | Paul |
| 2 | Annet |

children

| id |    name   |  
+----+-----------+
| 1 | Micheal |
| 2 | Susan |

和数据透视表parents_childs

| parent_id | child_id | custom_field_1 | custom_field_2 |  
+-----------+----------+----------------+----------------+
| 1 | 1 | value_1 | (null) |
| 2 | 1 | value_another | value_3 |

和标准关系belongsToMany

public function parents(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany('\App\Parent', 'parents_childs', 'child_id', 'parent_id')
->withPivot(
'custom_field_1',
'custom_field_2'
);
}

现在我需要更新指定子项的数据透视字段,但只针对一个父项,例如。

SET red_value FOR custom_field_2 WHERE child_id = 1 AND parent_id = 2

如果没有 QueryBuilder,我该如何做到这一点?

最佳答案

来自 the docs :

If you need to update an existing row in your pivot table, you may use updateExistingPivot method. This method accepts the pivot record foreign key and an array of attributes to update:

$child = Child::find($childId);
$child->parents()->updateExistingPivot($parentId, ['custom_field_2' => 'red_value']);

https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships

关于php - laravel - 更新与许多 'childs' 的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48020087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com