I want to use intermediate tables in Laravel! How to use the sync method
table of contents
thank you for your hard work!
My name is Yamada from the System Development Department.
This time, I will explain the sync method used when using intermediate tables in Laravel.
What is the sync method?
If the table relationship is many-to-many, I think the solution is basically to use an intermediate table.
At that time, it is an excellent tool that allows you to easily perform operations such as registering, updating, and deleting data in the intermediate table by using the sync method.
Let's take a look at some concrete examples.
Preparation (table configuration)
When using the sync method, assume the following situation.
- I want to link users and hobbies and add comments to the relationship.
- One user can have multiple hobbies
- One hobby can be selected by multiple users.
The table configuration to achieve the above is assumed as follows.
- users table that holds the names of users
id | name |
---|---|
1 | taro |
2 | hanako |
3 | saburo |
- Hobbies table to hold names of hobbies
id | name |
---|---|
1 | movie |
2 | youtube |
3 | study |
- Intermediate table (hobby_user table) that represents the relationship between users and hobbies and can add comments)
id | user_id | hobby_id | comment |
---|---|---|---|
1 | 1 | 1 | I quite like it |
2 | 1 | 2 | I quite like it |
3 | 2 | 1 | I quite like it |
We will proceed with the following discussion assuming that we have prepared a migration file in Laravel with the above contents, and inserted the data described in the users and hobbies tables.
Preparation (Laravel model file)
Write the following to represent a many-to-many relationship in the Laravel model file.
// hobby model public function users() { return $this->belongsToMany(User::class); } // users model public function hobbies() { return $this->belongsToMany(Hobby::class); }
Now that we are ready to use the sync method, we will use it from now on.
sync method
First of all, I would like to register the data.
If you want to add movies (hobby_id:1) to taro's (user_id:1) hobbies, you can express it as follows.
$user = User::find(1); $user->hobbies()->sync(1);
If you want to make comments or multiple registrations at once, you can express it as follows.
It is assumed that taro (user_id:1) will add youtube (hobby_id:2) and study (hobby_id:3) to his hobbies, and will also include comments.
$user = User::find(1); $user->hobbies()->sync([ 2 => ['comment' => 'I like it a lot'], 3 => ['comment' => 'I like it a lot' '], ]);
However, there is a caveat here.
is the DB when this code is executed on the DB with movies (hobby_id:1) added to taro's (user_id:1) hobbies
The data that added movies (hobby_id:1) to taro's (user_id:1) hobby has disappeared.
This is because the sync method, as the name suggests, is a method that synchronizes the specified data state.
*sync: Synchronization
By taking advantage of this synchronized nature, data can be easily deleted and updated.
Consider changing taro(id:1)'s hobby to the following.
youtube(hobby_id:2), study(hobby_id:3)⇒movie(hobby_id:1), youtube(hobby_id:2)
The current DB is as follows.
If you run this code below
$user = User::find(1); $user->hobbies()->sync([1,2]);
The result is below.
Normally, I would have deleted study (hobby_id:3) and then added movie (hobby_id:1), but by using the sync method I was able to do it in one go.
Also, the part you should know about the behavior is the id=2 part.
Comments are not specified this time, but they remain as they are.
This is because what is synchronized is only the relationship between the specified user_id and hobby_id, and hobby_id=2 does not need to be changed, so the record remains as is without being updated or deleted.
Application of sync method
We explained that the sync method is a method that synchronizes, but it is actually possible to just register without synchronizing.
The way to do that is to declare false as the second argument.
Continuing from the previous table, let's add study (hobby_id:3) to taro's (id:1) hobby.
$user = User::find(1); $user->hobbies()->sync(3, false);
By specifying false for the second argument, the movie (hobby_id:1) and youtube (hobby_id:2) that originally existed were not deleted, and the study (hobby_id:3) was successfully added.
However, setting false is an action that is easy to forget, and if you do not specify it, there is a risk of unintentionally erasing data.
Therefore, specifying the syncWithoutDetaching method instead of specifying false will have the same effect.
$user = User::find(1); $user->hobbies()->syncWithoutDetaching(3);
summary
This time, we introduced the sync method, which is useful when registering, changing, and deleting intermediate tables in Laravel.
I think this method is very easy to use once you understand the nature of synchronization.
Also, the syncWithoutDetaching method introduced at the end only executes the sync method with false specified internally in Laravel, but
by having such a method, you can prevent accidental mistakes. It's a very easy to use method.
Let's all master the sync method and enjoy coding every day!
Well then! !
lastly
I have opened the system development service site "SEKARAKU Lab" to which I belong.
Beyond is a one-stop service for everything from server design and construction to operation, so if you have any trouble with server-side development, please feel free to contact us.
SEKARAKU Lab: https://sekarakulab.beyondjapan.com/