3

Laravel 7.0 版

我有Team模型和User模型,team_has_users表。

team_has_users表有team_id, user_id,role列。

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

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

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_users表可以是这样的。

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

谁能帮我?

谢谢!

4

1 回答 1

1

附加时,您可以在传递时传递一个额外的数组。

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

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

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

检查文档同步部分,

于 2020-07-21T06:11:52.877 回答