laravel - 更新与许多'孩子'的关系

问题描述 投票:3回答:1

我有这个数据库: 父母

| 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,我怎么能这样做?

php laravel laravel-5
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.