2017-03-06 87 views
1

我的透视表含有总共3米栏:Laravel - 仅同步枢轴表的子集

  • USER_ID
  • ROLE_ID

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

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

我脑子里有几个解决方案:

选项一:

  1. 创建一个的UserRole新模式。
  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_ids_from_previous_query
  3. User::roles()->sync(list_of_merged_ids);合并$list_of_desired_ids_for_group_1

有没有另一种方法来做到这一点与雄辩?我认为选项(a)更容易实现,因为我不必合并2个ID和组的多维数组。而且,选项(a)可能需要更多的数据库,因为它需要在所有组行上运行DELETE和INSERT。

回答

1

我最终模仿Laravel sync()方法,但添加了一些额外的过滤。我将该方法添加到了我的Repository中,但它可以作为方法添加到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]);