laravel 多个 id 的 UpdateExistingPivot

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36694081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:37:47  来源:igfitidea点击:

UpdateExistingPivot for multiple ids

laravellaravel-5eloquent

提问by Victor

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

为了更新数据透视表中的单个记录,我使用了updateExistingPivot方法。然而,它需要 $id 作为第一个参数。例如:

$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?

但是如何一次更新数据透视表中的多个现有行?

回答by jwj

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.

您可以访问 BelongsToMany 关系中的 allRelatedIds() 方法,该方法将返回相关模型 ID 的集合,这些 ID 出现在与初始模型相对的数据透视表中。

Then a foreach will do the job:

然后 foreach 将完成这项工作:

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

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

回答by Priyabrata Atha

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.

您只能使用循环语句进行更新,因为 updateExistingPivot 函数只接受一维参数,请参阅 laravel 5.3 的核心函数。

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

Function: updateExistingPivot

功能: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()
]);

}