UpdateExistingPivot用于多个ID

Vic*_*tor 5 laravel eloquent laravel-5

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

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

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

小智 12

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

然后 foreach 将完成这项工作:

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

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

  • 旧答案,但仍然相关...您可以传递 ID 数组作为第一个参数,因此 `$step->contacts()->updateExistingPivot($step->contacts()->allRelatedIds()...`会工作得很好。 (4认同)