Laravel多对多与其他列同步 [英] Laravel Many to Many Sync with additional column
问题描述
Laravel 7.0版
Laravel version 7.0
我有 Team
模型和 User
模型, team_has_users
表。
team_has_users
表的 team_id
, user_id
,角色
列。
一个用户可以属于一个具有不同角色的团队。
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.
我尝试搜索并找到了一个类似的 syncwithoutDetaching
,但似乎不适合我的情况。
team_has_users
表可以是这样。
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
...
有人可以帮我吗?
谢谢!
推荐答案
附加时,您可以传递一个附加数组。
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']);
检查文档同步部分,
这篇关于Laravel多对多与其他列同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!