Laravel One of Many Eloquent Relationship Example
May 22, 2021, Originally published at techvblogs.com ・2 min read
A new one of many Eloquent relationships is coming to Laravel 8.42 thanks to a PR contribution by Lennart Carstens-Behrens along with collaboration from Taylor Otwell is released some days ago. This one of many relationships is very useful.
So what is one of many relationships 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.
Many times 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 BrowserHistory
models.
You may accomplish this using the hasOne
relationship type combined with the ofMany
methods:
// Get Latest Browser Historypublic function latestBrowserHistory(){
return $this->hasOne(BrowserHistory::class)->latestOfMany();
}
You may define a method to retrieve the “oldest”, or first, related model of a relationship:
// Get Oldest Browser Historypublic function oldestBrowserHistory(){
return $this->hasOne(BrowserHistory::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.
This new eloquent relationship ofMany
the method accepts the sortable column as its first argument and which aggregate function ( min
or max
) to apply when querying for the related model:
public function highestPriceProduct(){
return $this->hasOne(Product::class)->ofMany('price','max');
}
Thank you for reading this blog.