Monday, March 6, 2017

Laravel - Sync only a subset of the pivot table

My pivot table contains a total of 3 columns:

  • user_id
  • role_id
  • group

Group is just an integer. I would like to be able to sync the users and their roles but only the ones that belong to a specific group.

If I run a simple sync([1,2,3]) it will remove everything from the pivot table, ignoring the group altogether.

I have a few solutions in mind:

Option a:

  1. Create a new model for 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);

Option b:

  1. User::roles()->all();
  2. Fancy merge $list_of_desired_ids_for_group_1 with $list_of_ids_from_previous_query
  3. User::roles()->sync(list_of_merged_ids);

Is there another way to do this with Eloquent? I reckon option (a) is easier to implement as I don't have to merge 2 multidimensional arrays of IDs and groups. But also, option (a) might be more database intensive as it needs to run a DELETE and INSERT on all group rows.



via Danny H

Advertisement