Laravel - 仅同步数据透视表的子集

3

我的数据透视表包含3列:

  • user_id
  • role_id
  • group

其中,组只是一个整数。我希望能够同步用户和他们的角色,但只限于属于特定组的用户。

如果运行简单的sync([1,2,3]),它将从数据透视表中删除所有内容,完全忽略组信息。

我有几个解决方案:

选项a:

  1. 为UserRoles创建一个新模型。
  2. UserRoles::where('group', '=', '1');
  3. User::roles()->detach(list_of_ids_from_previous_query);
  4. User::roles()->attach(list_of_desired_ids_for_group_1);

选项b:

  1. User::roles()->all();
  2. 使用高级合并方法将$list_of_desired_ids_for_group_1$list_of_ids_from_previous_query合并
  3. User::roles()->sync(list_of_merged_ids);

是否有其他使用Eloquent的方法可以实现这一点?我认为选项(a)更容易实现,因为我不必合并两个多维数组的ID和组信息。但是,选项(a)可能更加耗费数据库资源,因为它需要在所有组行上运行DELETE和INSERT。

2个回答

2

我最终模仿了Laravel的sync()方法,但是添加了一些额外的过滤功能。我将该方法添加到了我的Repository中,但它也可以作为一个方法添加到Model中。

如果你想将该方法移动到一个Model中,可以像这样操作:

/**
 * Simulates the behaviour of Eloquent sync() but
 * only on a specific subset of the pivot
 * @param  integer $group
 * @param  array  $roles
 * @return Model
 */
public function syncBy($group, array $roles)
{
    // $this is the User model for example
    $current = $this->roles->filter(function($role) use ($group) {
        return $role->pivot->group === $group;
    })->pluck('id');

    $detach = $current->diff($roles)->all();

    $attach_ids = collect($roles)->diff($current)->all();
    $atach_pivot = array_fill(0, count($attach_ids), ['group' => $group]);
    $attach = array_combine($attach_ids, $atach_pivot);

    $this->roles()->detach($detach);
    $this->roles()->attach($attach);

    return $this;
}

使用方法:

$user= App\User::find(1);
// Will sync for user 1, the roles 5, 6, 9 but only within group 3
$user->syncBy(3, [5, 6, 9]);

0

你也可以像这样修改roles关系:

 /**
 * @return BelongsToMany
 */
public function roles(): BelongsToMany
{
    return $this->belongsToMany(
        app(UserRoles::class),
        'user_roles',
        'user_id',
        'role_id'
    )->wherePivot('group', 1);
}

然后只需使用简单的代码:

$user->roles()->sync($dataForSync);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接