Database tables 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 makes it easier to retrieve child data, and supports a variety of common relationships like:
One-to-one
The most basic relationship. If a User
model is associated with one Phone
model. To define this relationship, we will place a phone
method on the User
model. The phone
method should call the hasOne
method and return its result. The hasOne
method is available to your 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
The inverse of a hasMany
relationship, define a relationship method on the child model which 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 may be related to many Order
models, but you want to define a convenient way to interact with the most recent order the 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,