How to use intermediate tables in Laravel! How to use the sync method

Thank you for your hard work!
This is Yamada from the System Development Department.

This time, we will explain the sync method used when using intermediate tables in Laravel

What is the sync method?

When the table relationship is many-to-many, the basic solution is to use an intermediate table.
In this case, the sync method is a great way to easily perform operations such as registering, updating, and deleting data in the intermediate table.
Let's take a look at some specific examples.

Preparation (table layout)

When using the sync method, the following situations are assumed:

  • I want to link users with their hobbies and add comments to their relationships
  • One user can have multiple hobbies
  • A hobby is chosen by multiple users

The table configuration to achieve the above is assumed to be as follows

  • A users table that holds the names of users
id name
1 Taro
2 Hanako
3 saburo
  • A hobbies table that holds the names of hobbies
id name
1 movie
2 YouTube
3 study
  • An intermediate table (hobby_user table) that represents the relationship between users and hobbies and allows comments to be added
id user_id hobby_id Comment
1 1 1 I quite like it
2 1 2 I like it quite a bit
3 2 1 I quite like it

We will proceed with the following discussion assuming that you have prepared a migration file in Laravel with the above information and inserted the data described in the users and hobbies tables

Preparation (Laravel model file)

To represent a many-to-many relationship in a Laravel model file, write the following:

// 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 start using it from here

sync method

Let's start by registering some data.
If you want to add movies (hobby_id:1) to taro's (user_id:1) hobbies, you can do so as follows:

$user = User::find(1); $user->hobbies()->sync(1);

If you want to make a comment or register multiple things at once, you can do so as follows.
Let's add YouTube (hobby_id:2) and studying (hobby_id:3) to taro's (user_id:1) hobbies and also write a comment.

$user = User::find(1); $user->hobbies()->sync([ 2 => ['comment' => 'I like it quite a bit'], 3 => ['comment' => 'I like it moderately'], ]);

However, there is one thing to note here.

is the DB that will be generated when this code is executed on the DB in which movies (hobby_id:1) has been added to the hobbies of taro (user_id:1)

The data for adding movies (hobby_id:1) to taro's (user_id:1) hobbies has disappeared.
This is because the sync method, as its name suggests, synchronizes the data state with the specified content.
*sync: Synchronization

By using this synchronization feature, you can easily delete and update data.
Let's consider changing taro's (id:1) hobbies to the following:
youtube (hobby_id:2), studying (hobby_id:3) ⇒ movies (hobby_id:1), youtube (hobby_id:2)

The current DB is as follows:

If you run the following code:

$user = User::find(1); $user->hobbies()->sync([1,2]);

The results are as follows:

Normally, you would delete Studying (hobby_id:3) and add Movies (hobby_id:1), but by using the sync method, you can do this in one go.
Also, the part you want to be aware of in terms of behavior is the id=2 part.
Although no comments are specified this time, 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 the sync method

We explained that the sync method is a synchronization method, but it is actually possible to register without synchronization. To
do this, declare the second argument as false.
Continuing with the previous table, let's add studying (hobby_id:3) to taro's (id:1) hobbies.

$user = User::find(1); $user->hobbies()->sync(3, false);

By specifying false as the second argument, the existing movies (hobby_id:1) and youtube (hobby_id:2) were not deleted, and study (hobby_id:3) was successfully added.
However, it is easy to forget to specify false, and if you do not specify it, there is a risk of unintentionally deleting data.
Therefore, the same effect can be achieved by specifying the syncWithoutDetaching method instead of specifying false.

$user = User::find(1); $user->hobbies()->syncWithoutDetaching(3);

summary

This time, we introduced the sync method, which is useful when registering, updating, or deleting intermediate tables in Laravel.
I think it is a very easy-to-use method as long as you understand the nature of synchronization.
Also, the syncWithoutDetaching method introduced at the end simply executes the sync method with false set internally in Laravel, but
having such a method available helps prevent careless mistakes, making it a very handy method.

Let's all master the sync method and enjoy coding every day
!

lastly

I have launched a system development service site called "SEKARAKU Lab," which I work for.
Beyond can handle everything from server design and construction to operation, so if you have any problems with server-side development, please feel free to contact us.
SEKARAKU Lab: https://sekarakulab.beyondjapan.com/

If you found this article useful, please click [Like]!
5
Loading...
5 votes, average: 1.00 / 15
13,373
X Facebook Hatena Bookmark pocket

The person who wrote this article

About the author

Yuki Yamada

Joined Beyond Inc. in 2021.
His hobbies are karaoke and board
games. He wants to buy a new shelf because he can no longer fit all his board games on one, but is sad that he has no space at home for a shelf.
He has also had experience in mold design and sales, and has gained a wide range of experience, settling into a job as a server-side engineer. He is
currently engaged in server-side development using PHP and Python.
He would like to learn a front-end language in the future, and is interested in Next.js, a React-based front-end framework.