【问题标题】:UpdateExistingPivot for multiple ids多个 id 的 UpdateExistingPivot
【发布时间】:2016-08-10 04:43:41
【问题描述】:

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

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

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

【问题讨论】:

  • 不确定,但尝试放一个带有 ids 的数组
  • 我试过了,还是不行:(
  • 可能是bug,好像可以工作stackoverflow.com/a/30756967/4581725
  • 但这只是旧 Laravel 版本的链接。它在 Laravel 5 上不能这样工作。

标签: laravel laravel-5 eloquent


【解决方案1】:

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

然后一个 foreach 将完成这项工作:

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

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

【讨论】:

  • 仅供参考,该方法现在命名为allRelatedIds
  • 旧答案,但仍然相关...您可以将 ID 数组作为第一个参数传递,因此 $step->contacts()->updateExistingPivot($step->contacts()->allRelatedIds()... 可以正常工作。
【解决方案2】:

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

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

功能:更新ExistingPivot

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

所以,你应该遵循简单的过程:

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

}

【讨论】:

    猜你喜欢
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 2015-05-24
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多