Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sync table based on pivot column value

I have this schema for the M-M table in laravel 9

Schema::create('role_user', function(Blueprint $table)) {
  $table->bigInteger('role_id')->unsigned();
  $table->foreign('role_id')->references('id')->on('roles');

  $table->bigInteger('user_id')->unsigned();
  $table->foreign('user_id')->references('id')->on('users');

  $table->bigInteger('business_unit_id')->unsigned();

  $table->primary(['role_id', 'user_id', 'business_unit_id']);
}

The idea is that for each business unit the user has a different role.

I tried to save the data using:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$user->roles()->syncWithoutDetaching([$role->id => ['business_unit_id' => $businessUnitId]]);

is not working properly…

How can I sync all the data based on the current ‘business_unit_id’ without touching the other entries (with other business_unit_id) ?

>Solution :

To sync all the data based on the current ‘business_unit_id’ without touching the other entries (with other business_unit_id), you can use the wherePivot method in Laravel. Here’s an example:

$user->roles()->wherePivot('business_unit_id', $businessUnitId)->sync([$role->id]);

This will synchronize the pivot table for the given user and role, but only for the specified business_unit_id. The wherePivot method filters the pivot table records by the specified condition before performing the sync operation.

Note that the sync method replaces all existing entries in the pivot table for the given user and role, so you may want to use syncWithoutDetaching if you want to add the new record without deleting the existing ones.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading