Php Laravel与附加列多对多同步
Laravel 7.0版 我有Php Laravel与附加列多对多同步,php,laravel,eloquent,laravel-query-builder,laravel-relations,Php,Laravel,Eloquent,Laravel Query Builder,Laravel Relations,Laravel 7.0版 我有团队模型和用户模型,团队有用户表格 team\u有用户表有team\u id,user\u id,角色列 一个用户可以属于一个具有不同角色的团队 例如,一个用户可以作为客户和员工属于一个团队 在Team模型中,我设置了这样一个关系 public function users(){ return $this->belongsToMany(User::class, 'team_has_user', 'team_id', 'user_id') -
团队
模型和用户
模型,团队有用户
表格
team\u有用户
表有team\u id
,user\u id
,角色
列
一个用户可以属于一个具有不同角色的团队
例如,一个用户可以作为客户和员工属于一个团队
在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']);
team_id user_id role
1 1 client
1 1 employee
1 2 client
1 1 other
...
当我将用户添加到团队中时,它就像这样工作得很好
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']);
team_id user_id role
1 1 client
1 1 employee
1 2 client
1 1 other
...
但是,当我要同步它们时,我做不到
我尝试搜索并找到了一个类似的syncwithoutDetaching
,但它似乎不适合我的情况。
team\u拥有用户
表可以是这样的
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']);
team_id user_id role
1 1 client
1 1 employee
1 2 client
1 1 other
...
有人能帮我吗
谢谢大家! 当附加时您可以传递一个附加数组
$item->users()->attach($request->clients, ['role'=>'client']);
$item->users()->attach($request->employees, ['role'=>'employee']);
但在同步过程中,必须在数组内传递枢轴值,我在下面提到了一个示例
$item->roles()->sync([1 => ['role' => 'client'], 2 => ['role' => 'employee']);
选中同步部分,谢谢,我不能执行
$item->users()->sync($request->clients,['role'=>'client']
?我应该单独分割数组吗?不,你不能。在同步时,你必须分配pivot的值。因此你必须创建数组。[$clientid=>['role'=>'client'],[$employeeid=>['role'=>'employee']
如果$request->clients
和$request->employees
具有相同的id,则此操作不起作用。这是因为团队id
和用户id
与client
和employees
具有相同的id。否则,根据您的问题,这是正确的解决方案。您设计了错误的数据库。我们已经有了er+角色有关系,在您的情况下,您的DB设计错误。