2016-04-18 4 views
3

ピボットテーブルで1つのレコードを更新するには、updateExistingPivotメソッドを使用します。しかし、最初の引数として$ idが必要です。例:複数のidsのUpdateExistingPivot

$step->contacts()->updateExistingPivot($id, [ 
    'completed' => true, 
    'run_at' => \Carbon\Carbon::now()->toDateTimeString() 
]); 

しかし、ピボットテーブルの既存の複数の行を一度に更新するにはどうすればよいですか?

+0

わからないが、しかし、そこに私が試したIDS – apelsinka223

+0

持つ配列を配置しようと、それはなかったの't仕事:( – Victor

+0

これはバグかもしれないが、それは仕事のようだhttp://stackoverflow.com/a/30756967/4581725 – apelsinka223

答えて

1

アクセス可能なBelongsToManyリレーションにはgetRelatedIds()メソッドがあり、初期モデルに対してピボットテーブルに表示される関連モデルのIDのCollectionを返します。

その後、foreachのは仕事をする:

$ids = $step->contacts()->getRelatedIds(); 

foreach ($ids as $id){ 
    $step->contacts()->updateExistingPivot($id, ['completed' => true]); 
} 
0

機能のみlaravel 5.3用のコア機能を参照してください、1次元のparamsを受け入れるがupdateExistingPivotとしてあなたが唯一のループ文を使用して更新することができます。

File: yoursite\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations\BelongsToMany.php 

機能:

public function updateExistingPivot($id, array $attributes, $touch = true) 
    { 
     if (in_array($this->updatedAt(), $this->pivotColumns)) { 
      $attributes = $this->setTimestampsOnAttach($attributes, true); 
     } 

     $updated = $this->newPivotStatementForId($id)->update($attributes); 

     if ($touch) { 
      $this->touchIfTouching(); 
     } 

     return $updated; 
    } 

のでupdateExistingPivotは、あなたは単純なプロセスに従う必要があります。

$step = Step::find($stepId); 
foreach(yourDataList as $youData){ 
    $step->contacts()->updateExistingPivot($youData->contract_id, [ 
    'completed' => true, 
    'run_at' => \Carbon\Carbon::now()->toDateTimeString() 
]); 

}