UpdateExistingPivot for multiple ids

2019-06-22 16:02发布

问题:

In order to update single record in pivot table I use updateExistingPivot method. However it takes $id as the first argument. For example:

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

But how can I update multiple existing rows in pivot table at once?

回答1:

There's an allRelatedIds() method in the BelongsToMany relation that you can access, which will return a Collection of the related model's ids that appear in the pivot table against the initial model.

Then a foreach will do the job:

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

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


回答2:

You can update only by using a looping statement as there updateExistingPivot function only accept one dimensional params, See the core function for laravel 5.3.

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

Function: updateExistingPivot

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

So, You should follow the simple process:

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

}