多个ID的UpdateExistingPivot [英] UpdateExistingPivot for multiple ids

查看:96
本文介绍了多个ID的UpdateExistingPivot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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.

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

Then a foreach will do the job:

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

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

这篇关于多个ID的UpdateExistingPivot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆