2017-12-29 13 views
3

내가 가진이 데이터베이스와 관련 업데이트 :
부모laravel - 많은 '차일'

| 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' 
       ); 
} 

이제 특정 부모의 피벗 필드를 업데이트해야합니다. 예 :

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

어떻게하면 QueryBuilder없이이 작업을 수행 할 수 있습니까? the docs에서

답변

1

: 당신이 당신의 피벗 테이블의 기존 행을 업데이트해야하는 경우

, 당신은 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

:이 방법은 업데이트 할 피벗 기록 외래 키와 속성의 배열을 받아