One-to-many relationship in Laravel explanation and eager loading, how to use?

How to use one-to-many relationships in Laravel and eager loading

One-to-many and many-to-one relationships are most commonly used in web programming.

Let's start with a simple example of this relationship. For example, one person has many bank cards and each of these cards belongs only to this person or user has a lot of comments and each comment belongs to this user.

How to use one-to-many relationships in Laravel and eager loading 2

One-to-many and many-to-one relationships in Laravel are implemented as follows.

Initially, you should decide whether you will use the Laravel table and key naming conventions.

This guide follows all naming conventions to make the examples easier to understand and describes the benefits of eager loading. All requirements and preferences for database tables are described in the documentation of this framework.

Let's use a simple example of users and their posts.

Create two tables: Users, Posts.

How to use one-to-many relationships in Laravel and eager loading 3

Define two models: User and Post. - (model names in singular).

In model User:

public function posts() {
            //--- Function name in plural
            //--- Referencing to Many
// Referencing from parent to child
return $this->hasMany(Post::class);

In model Post:

public function user() {    
            // ---   In the singular 
            // ---   Referencing to One
// Referring from child to parent
return $this->belongsTo(User::class);  

Eager Loading (preferred)

Only one query is made to the database, retrieving data and relationships. And at the next interaction with properties and their relationships within the application, the database is no longer affected. This gives a huge savings in resources, especially noticeable on large projects.

Eager loading is defined by calling the with() function, which is passed the names of the functions specified in the models as a string.

Data fetching using Eager Loading.

An example of selecting a user with (id 1) and all his posts:

User::with('posts')->where('id', 1)->get();

Let's look at another example and imagine that a user's posts have comments. Now we need to select all posts and comments for the same user.

User::with('posts.comments')->where('id', 1)->get(); 

How to find out who is the author of the post with (id 1)? To do this, we use the many-to-one relationship.

Post::with('user')->where('id', 1)->get();

Now let's complicate the example and find out which posts the comment with (id 1) belongs to and who the authors of these posts are (if any).

Comment::with('post.user')->where('id', 1)->get();

How to get the result of all relationships of different directions both for one and for all users?

How to use one-to-many relationships in Laravel and eager loading 10

Let's change the previous example and select now the user with (id 1) and all his posts, as well as comments to them, this is a relationship (one to many), but we want to get all the titles of these posts, this is a relationship (one to one), How to do it ? Just list the relationships by separating them with a comma in the with() function.

$users =
User::with(['posts.comments', 'posts.description'])->where('id', 1)

You can create huge relationship chains and easily access any table in a clean and simple way while getting an optimized database query with Eager Loading in Laravel. Accordingly, you first need to add functions to the model: hasMany, hasOne и belongsTo as much as needed. It is important to correctly specify the order of functions.

Lazy Load (not recommended)

Used by default when accessing properties and their relationships in an application every time the database is affected. For example, there are 50 comments, and on each iteration of the loop, a database query will be executed. Total 51 queries.

@foreach ($users as $user)

If you have any difficulties understanding or implementing, we are always ready to help you with this, feel free to contact us.

Author: Yuriy Lisenko