Laravel 多对多与附加列同步

Laravel Many to Many Sync with additional column

Laravel 版本 7.0

我有Team型号和User型号,team_has_userstable。

team_has_users table 有 team_iduser_idrole 列。

一个用户可以属于一个具有不同角色的团队。

例如,一个用户可以作为客户和员工属于一个团队。

Team模型中,我设置了这样的关系。

public function users(){
   return $this->belongsToMany(User::class, 'team_has_user', 'team_id', 'user_id')
       ->withPivot('role');
}

当我将用户添加到团队时,效果很好。

    $item->users()->attach($request->clients, ['role'=>'client']);
    $item->users()->attach($request->employees, ['role'=>'employee']);

但是,当我要同步它们时,我做不到。

我尝试搜索并找到了一个类似的 syncwithoutDetaching,但它似乎不适合我的情况。 team_has_userstable可以这样

team_id    user_id    role
1           1         client
1           1         employee
1           2         client
1           1         other
...

谁能帮帮我?

谢谢!

虽然 attach 您可以传递一个额外的数组。

$item->users()->attach($request->clients, ['role'=>'client']);
$item->users()->attach($request->employees, ['role'=>'employee']);

但是在同步中你必须在数组中传递枢轴值,我在下面提到了例子。

$item->roles()->sync([1 => ['role' => 'client'], 2 => ['role' => 'employee']);

检查documentation同步部分,