Learn about Relationships in Laravel

Tram Ho

In life, everything is connected, for example, a book must have an author, or a school must have many classes. Also in the database, tables can also be linked. Laravel has provided us with relationships that can reduce the time and effort of the programmers. It makes it easier to query tables. In this article we learn about the types of relationships together

  • One to One
  • One to Many
  • Many to Many
  • Has One Through
  • Has Many Through
  • Polymorphic Relations

Relationships in Laravel

1. One to One

This is the simplest type of relationship, which we can understand that one depends only on the other and vice versa. For example, to make it easy to imagine, we have the Users table and the Avatar table, here one user has only one avatar and this avatar only represents that user. To express this relationship, we use the hasOne method

Above we see that the first parameter passed in the hasOne method is the name of the model associated with that table. When we declare like that, if we want to get the avatar of the user whose id is 1 for example, we simply do like this.

Notice above Eloquent will automatically match the foreign key column with the user_id name of the Avatar table corresponding to the id field of the User table, if in the case the foreign key is not set to user_id but sets a different name, we need to pass a second parameter 2.

Similarly, if the primary key of the table you are linking to is not id then you need to pass a third argument to make it understand that the foreign key of this column corresponds to the primary key with the other column.

Inverse

In the previous example, we can from a user to call the corresponding avatar of that user, now we will also be able to query the same from this avatar to query out the user that belongs to it.
In the above example, Eloquent automatically matches the user_id column in the Avatar table with the id column of the User table. In Eloquent, the default foreign key confirmation is the omitted table name ‘s’ _id , in this case the user_id . If the foreign key in the Avatar not set in accordance with the previous standard, it will need to declare one more second parameter.

If you do not want the foreign key map of the Avatar table with the id column in the User table but another column, for example, continue adding a third parameter as follows.

2. One to Many

This relationship to signify a parent-child relationship. For example, a user will have many posts . Then this relationship will be expressed as follows.

Similarly, the One-One Eloquent relationship will automatically find the foreign key on the Post model, in this case the eloquent will find the foreign key “snake case” model name _id , in the example above will be user_id , Eloquent will be fake. user_id is foreign key in the Post model. To query to multiple posts belonging to a user is simple by:

and vice versa

3. Many to Many

This relationship is more complicated than the previous two. For example, a product will belong to many orders but an order has many products . To represent this relationship, we need to use a third table, we will name order_product . and also will contain 2 columns, order_id and product_id . In this relationship, we will use the belongsToMany method. Example of representing the Product method with the order table

Now want to retrieve a product how many order , just need

Note that, Eloquent will automatically find the intermediate table named in alphabetical order, in this case the table will be named order_product . However, if you want to name something else that is not a convention like product_order then just pass the second argument to the belongsToMany method.

Similarly, you can also customize the names of the two names of the associated columns, corresponding to the 3rd and 4th belongsToMany of the belongsToMany method. The third parameter will be the foreign key of the table defining the relationship and the fourth parameter is the table we want to join. For example in this case.

In contrast, for the Order table we define the following:

And we are similar to the definition of the Product model, we can also pass parameters if we want

Get the value of the intermediate table To work with this Many to Many relationship, we need to use an intermediate table. Eloquent also helps us derive the values ​​of this table. To access the intermediate table columns we will use the pivot attribute. For example :

By default, Eloquent only takes intermediate fields and created_at , update_at if we want to retrieve the value of another column, we need to declare more as follows, assuming we need to get additional address fields.

Or when you want the created_at and update_at fields of the intermediate table to automatically update values, then declare more

Sometimes users want to change the name of the pivot attribute, so what should they do, just use the as method declared in the model? For example

Now you want to access the properties of the intermediate table that replace pivot with newname .

Another question is that if you want to get products with the condition of intermediate tables, it will be like, very simple, Laravel also supports us in this regard.

Here, we will retrieve orders with prices greater than 20,000.

4. Has One Through

This is a relationship that links tables together through an intermediate table. For example, there are 3 tables:

Although the history table is not supplier_id , we can still access user's history by hasOneThrough relationship as follows:

With the first parameter passed as the name of the model we want to access, the second parameter is the intermediate model. We can also customize the keys related to this relationship as the following parameters to the relationship definition function.

We have the user and history tables defined as usual

5. Has Many Through

This has many through relationship provides us with an easier way to access linked tables through intermediate tables. For example, a Team has many Post through intermediate tables as User .

Although board posts do not contain foreign key team_id , but with relations hasManyThrough will give us get all posts of teams by $team->posts . To do this, Eloquent will check team_id through the users table. We will show the following relationship:

The first parameter of this relationship is the model name we want to access, the second parameter is the intermediate model. We can also customize the name of the foreign key by adding parameters, with the third parameter being the foreign key of the intermediate table, the fourth parameter is the foreign key of the table we want to call, the parameter 5th is the field we want to link to in the table we are using, the 6th parameter is the field we want to link to in the intermediate table.

6. Polymorphic

This is a polymorphic relationship in Laravel that allows one Model to belong to many other Models with only one associate.

6.1 One to One Polymorphic

This relationship is similar to the One to One relationship, but the purpose of this relationship is that one model can belong to one or more other models. For example, a post has an image and a product also has an image , if normal, you must create two more tables: post_image to save the image of the post and product_iamge to save the image of the product , if there are billions of tables needed Image has to create more tables to save the image, so it will be too complicated and confusing, thus creating this polymorphic relationship. For example :

This is the way to build this polymorphic relationship. With imageable_id id of the posts table and the products table will be saved, while the imageable_type field will store the Post and Product model class names. According to laravel’s convention, the intermediate storage table will require 2 id and type fields, but for more clarity, it will save the prefix tên_bảng_bỏ_s +able_ . Model structure

To retrieve an image belonging to posts , it will point to the image .

and vice versa from image can be inferred by post or product depending on it.

6.1 One to Many Polymorphic

This relationship is similar to the One to Many relationship. For example, a User can comment on both Post and Video , only need a comments table in this case

Model structure

Retrieving the value of all the comment on the post we do is as follows

or from comment to get back the post or videos belong to it

6.1 Many to Many Polymorphic

This relationship will be a bit more complicated. For example, a good post or video may have lots of tags . Using a many to many polymorphic allows you to query to retrieve tags belong to a post or video


Model structure


Ok now want to retrieve the tag belonging to a post we do the same but the other relationship.

or vice versa
Share the news now

Source : Viblo