Database tables are mostly related to one another. For example, a post may have many comments or an order that can be related to the person who placed it. Eloquent use makes it easier to retrieve child data and supports a variety of common relationships.
One-to-one
The most basic relationship. If a User
model is associated with one Phone
model. To define this relationship, we can place a phone
method in the User
model. This method should call the hasOne
method and give its result. The hasOne
method is available in a model as shown below.
public function phone()
{
return $this->hasOne(Phone::class);
}
One-to-many
If we have Authors and Books, with 1-n (one-to-many) relationship – one Author can have one or many Books. Here’s how the code looks.
public function books()
{
return $this->hasMany(Book::class, 'author_id');
}
Belongs-to
It is the inverse of a hasMany
relationship, and defines a relationship method on the child model that calls the belongsTo
method. We use it as shown below.
public function post()
{
return $this->belongsTo(Post::class);
}
Has One of Many
Used when you want to retrieve the “latest” or “oldest” related model of the relationship. For example, a User
model can be related to many Order
models, but you can define a convenient way to interact with the most recent order a user has placed. The code below shows how to relation can be used.
public function latestOrder()
{
return $this->hasOne(Order::class)->latestOfMany();
}
One of the functionality of these Eloquent relations is to filter parents by whether they have or don’t have children. They help manage, work, and retrieve child data using with these relationships.