Laravel Many to Many Sync with additional column

南楼画角 提交于 2020-08-07 15:58:10

问题


Laravel version 7.0

I have Team model and User model, team_has_users table.

team_has_users table has team_id, user_id, role columns.

One user can belong to one team with different roles.

For instance, one user can belong to one team as a client and as an employee.

in Team model, I set a relation like this.

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

When I attach users to the team, it worked well like this.

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

But, when I was going to sync them, I couldn't do.

I tried to search and found a similar one syncwithoutDetaching but it seems not to fit for my case. team_has_users table can be like this.

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

Can anyone help me?

Thank you!


回答1:


While attach you can pass an additional array as you have passed.

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

But In the sync you have to pass pivot value inside the array, I have mention example below.

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

Check documentation sync part,



来源:https://stackoverflow.com/questions/63008368/laravel-many-to-many-sync-with-additional-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!