1 to N relationships with Laravel Eloquent

How to define models and how to access data from related tables, in one-to-many (1 to N) relationships, using Laravel Eloquent.

We continue the Laravel Manual by addressing a basic topic within Eloquent, the Laravel ORM. We will see what is known as one-to-many relationships, also called 1-to-N relationships, which are a very common type of relationship between tables.

We’ll walk through the practice of building models, and then we’ll look at code to use those models and access data from related models. We will see that Laravel and Eloquent make things much easier and offer us very high-level mechanisms to access information, in both directions.

When is a 1 to N relationship generated?

Let’s start by quickly clarifying when you have a one-to-many relationship in relational database design, although we hope most of you have this understanding.

One-to-many relationships occur when we have two tables in the database and one of them is related to the other, such that table “A” has many related table “B” items and table ” B” only relates to an element of table “A”. It is best seen with an example.

Suppose we have a database of articles with their authors and that each article is written by a single author. Well, here we can say that:

  • An article relates to a writer.
  • A writer can write many articles.

As you can see in the previous image, the N is on the side of the article. We can say that this relationship is 1 writer with N articles.

How to design the database tables

In the design of the database, for this type of relationship, in the table of the relationship that is marked by N, the identifier or primary key of the table that is marked with 1 is placed. Therefore, one of the fields of the article table will be the escritor_id, which will have the identifier of the author of that article.

The writer_id (or writer_id, because we already know the recommendation to write English table names in Laravel) in the “article” table is said to be a foreign key.

Remember that the issue of migrations for the creation of the tables and the relationships between them is something that we have already addressed in the article Indexes and keys in Laravel migrations. /articulos/indices-claves-migraciones-laravel.html

Defining relationships in models with Eloquent

Now we are going to address the most fundamental part of Laravel development for 1 to N relationships, which is to conveniently create the models for us to inform the framework of the existence of this relationship. Since you already know how to create models in Laravel /articulos/laravel-eloquent.html we are going to go directly to the part of the relations.

To define the relationships we will have to specify methods with a concrete form, in which we inform about the relationships. Since the relationship affects two tables, we will have two models to work with.

Suppose we have the names of the tables in English. We have the “articles” table and the “writers” table. So we will have two models “Article” and “Writer”.

1-to-many relationship in the Writer model

We start with the relationship that we have in the “1” part, that is, in the table that is related to “N” elements of the other part. In our case it is the “Writers” table that has the “1” and that is related to “N” articles. We say that 1 writer has many articles authored by him.

To define the relationship, we have to create a method in the model, with the name that we want to give to said relationship, which will usually be the name of the entity that we want to relate to, in this case in the plural, since a writer can be related to many articles.

hasMany(‘App\Article’); } }

The articles() method is the one that implements the relationship. In it we have to return the return value of the hasMany() method of the Eloquent models. We have to inform hasMany with the name of the class of the model with which we are relating.

Laravel will automatically understand that the foreign key will exist in the “articles” table with the writer who is the author (writer_id in the article table) and that in the local table (writers), the primary key is called “id”. It’s important that we respect table and foreign key naming conventions, so we don’t have to do any more work defining relationships, but if this isn’t the case, hasMany() can also take as parameters customizations to tables that are necessary.

For example, if the foreign key in the article table had a name other than writer_id, we could indicate it like this:

return $this->hasMany(‘App\Article’, ‘foreign_key_name’);

And if it were the case that in the writers table the primary key was not called “id” we could also indicate it with this call to hasMany():

return $this->hasMany(‘App\Article’, ‘foreign_key_name’, ‘local_primary_key_name’);

Access to related table data

Once we have the relationship defined in our model, we can access the data from the related table in any Writer model. For this we use the name of the method that we have created as a relation, in this case it was “articles”.

$articles_by_an_author = App\Writer::find(1)->articles;

This will be a collection of items that we can use like any other Laravel collection.

foreach($articles_by_one_author as $article) { // do whatever you need for each $article }

In Laravel, access to the data of the related tables is done by “lazy load”, which means that, until these related fields are accessed, the corresponding query for the relationship will not be made. But we can force Eloquent to bring us the related data beforehand.

$writers = Writer::with(‘articles’)->get();

The inverse of the 1 to N relationship, in the Article model

By defining the article model we can also, if necessary, define the relationship. With this we achieve that it is very easy to access from the model marked with the “N” to the data of the model marked with the “1”. In other words, for our example, access the writer who has written a certain article.

This is achieved by defining a method in the model, which will have whatever name we want, but it will usually be the name of the entity we want to relate to. In this case in the singular, since we are only relating to an element of the other table. In the case of our article, we want to relate to a single writer.

belongsTo(‘App\Writer’); } }

As you can see, the method that receives the inverse 1 to N relationship contains the return of the belongsTo() method, in which we indicate the name of the model we are relating to.

In the same way as in the previous case, it is important that the tables are created with the conventions that Eloquent assumes. In the article table it is understood that the name of the foreign key field is called “writer_id” and that the name of the primary key of the related table is “id”. If this were not the case, we have to teach Eloquent by indicating as parameters the names that have been used in the definition of the tables.

return $this->belongsTo(‘App\Writer’, ‘foreign_key_name’, ‘other_table_key_name’);

Note: As you can see, the conventions save us a lot of work when developing the models, both by putting the names of the tables in English and in the plural, as well as using “id” as the primary key, and the name of the entity followed by “_” and then “id” as the foreign key.

conclusion

This is the summary of the most essential knowledge to comfortably implement all the necessary infrastructure in Eloquent to implement relationships between models, from one to many.

Laravel makes things very easy for you and thanks to these relations it will be very easy to access the data of the related tables from 1 to N.

See also  layered model
Loading Facebook Comments ...
Loading Disqus Comments ...