我有这个数据库:
父母
| id | name |
+----+--------+
| 1 | Paul |
| 2 | Annet |
孩子
| 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'
);
}
现在我需要更新指定子节点的pivot字段,但仅限于一个父节点,例如。
SET red_value FOR custom_field_2 WHERE child_id = 1 AND parent_id = 2
如果没有QueryBuilder,我怎么能这样做?
答案 0 :(得分:1)
来自the docs:
如果您需要更新数据透视表中的现有行,可以使用
updateExistingPivot
方法。此方法接受数据透视记录外键和要更新的属性数组:
$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