【问题标题】:Laravel Many to Many Sync with additional columnLaravel 多对多同步与附加列
【发布时间】:2020-11-10 11:18:05
【问题描述】:

Laravel 7.0 版

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

team_has_users 表有 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_users表可以这样。

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

谁能帮帮我?

谢谢!

【问题讨论】:

    标签: php laravel eloquent laravel-query-builder laravel-relations


    【解决方案1】:

    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同步部分,

    【讨论】:

    • 谢谢,我不能$item->users()->sync($request->clients, ['role'=>'client'] 吗?
    • 要不要单独分割数组?
    • 不,你不能。在同步中,您必须分配枢轴的值。因此你有制作数组。 [$clientid=>['role'=>'client'],[$employeeid=>['role'=>'employee']]
    • 如果$request->clients$request->employees 有一些相同的ID,这不起作用。
    • 这不起作用,因为team_iduser_id 对于clientemployee 是相同的。否则,根据您的问题,这是正确的解决方案。您设计了错误的数据库。用户+角色已经有关系,在你的情况下你做了错误的数据库设计。
    猜你喜欢
    • 2018-12-16
    • 2021-01-13
    • 2021-12-21
    • 2015-01-29
    • 2016-06-15
    • 2018-07-23
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多