Laravel One of Many Eloquent Relationship Example

Hello Artisan A new “one of many” Eloquent relationship is coming to Laravel 8.42 thanks a PR contribution by Lennart Carstens-Behrens along with collaboration from Taylor Otwell is released somedays ago. This one of many relationship is very useful so that i am here to help you to learn about it.

So what is one of many relationship is? The one-of-many relationship creates a one-to-one association from a one-to-many relationship. This quote is not enough to define this relationship. So let's see an example to understand.

Manytime you will see that a model may have many related models, yet you want to easily retrieve the "latest" or "oldest" related model of the relationship. For example, a User model may be related to many Order models.

But in this case you want to define a convenient way to interact with the most recent order the user has placed. You may accomplish this using the hasOne relationship type combined with the ofMany methods:

/**
 * Get the user's most recent order.
 */
public function latestOrder()
{
    return $this->hasOne(Order::class)->latestOfMany();
}

 

Likewise, you may define a method to retrieve the "oldest", or first, related model of a relationship:

/**
 * Get the user's oldest order.
 */
public function oldestOrder()
{
    return $this->hasOne(Order::class)->oldestOfMany();
}

 

Here in this query by default, the latestOfMany and oldestOfMany methods will retrieve the latest or oldest related model based on the model's primary key, which must be sortable.

However, manytimes you need to retrieve a single model from a larger relationship using a different sorting criteria. For example, using the ofMany method, you may retrieve the user's most expensive order.

This new eloquent relationship ofMany method accepts the sortable column as its first argument and which aggregate function (min or max) to apply when querying for the related model:

/**
 * Get the user's largest order.
 */
public function largestOrder()
{
    return $this->hasOne(Order::class)->ofMany('price', 'max');
}

 

Recommended: API Authentication Tutorial with Laravel Passport

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js