首页 > 解决方案 > 如何在 3 列数据透视表中使用同步?

问题描述

Pivot: team_member
team_id  |  member_id  |  status  |
-----------------------------------
   1     |      1      |    1     |
   1     |      2      |    1     |
   2     |      3      |    1     |
   3     |      4      |    1     |

如何使用同步功能将最后一条记录更新为状态 0?

$team = Team::find(3);
$member_ids = [4];
$status = 0;

$team->members()->sync($member_ids, ['status' => 0]);

如果 team_id 和 member_id 与现有的相同,则同步不起作用。

团队模型

   public function members() {
        return $this->belongsToMany(Member::class, 'team_member', 'team_id', 'member_id')->withPivot('status');
    }

标签: phplaravel

解决方案


尝试使用这个:

更新数据透视表上的记录

如果您需要更新数据透视表中的现有行,您可以使用 updateExistingPivot 方法。此方法接受数据透视记录外键和要更新的属性数组:

$team->members()->updateExistingPivot($memberId, ['status' => 0]);

资源

问候


推荐阅读