"One of Many" Eloquent Relationship Added to Laravel

News

May 18th, 2021

one-of-many-featured.png

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 (and others) in framework pull request #37362:

The one-of-many relationship creates a one-to-one association from a one-to-many relationship. For example, “latest login,” “first login,” and product pricing (i.e., get the latest published price for a product).

The implementation works by filtering the intersection of the relation joined on itself. A query example from the pull request helps illustrate how it works under the hood:

1SELECT *
2FROM `logins`
3INNER JOIN (
4 SELECT MAX(id) AS id
5 FROM logins
6 GROUP BY logins.user_id
7) AS latest_login
8ON latest_login.id = logins.id

Continuing the example of a User model that has many logins, hre’s a code example of defining a one-of-many realationship using Eloquent:

1class User extends Model
2{
3 public function latest_login()
4 {
5 return $this->hasOne(Login::class)->ofMany();
6 }
7}

And here’s the interface associated with ofMany:

1interface SupportsPartialRelations
2{
3 /**
4 * Indicate that the relation is a single result of a larger one-to-many relationship.
5 *
6 * @param string|array|null $column
7 * @param string|Closure|null $aggregate
8 * @param string|null $relation
9 */
10 public function ofMany($column = 'id', $aggregate = 'MAX', $relation = null);
11 
12 /**
13 * Determine whether the relationship is a one-of-many relationship.
14 *
15 * @return bool
16 */
17 public function isOneOfMany();
18}

The PR includes two helper methods if you are looking for more expressiveness in the relationship:

1$this->hasOne(Login::class)->latestOfMany();
2$this->hasOne(Login::class)->oldestOfMany();

Documentation is forthcoming soon, so the best place to learn more is the description and discussion in Pull Request #37362. The description outlines drawbacks from using hasOne for this type of relationship, which should be helpful for your understanding of when to use this type of relationship.

The author of the PR also provided a GitHub repo with ofMany() examples: cbl/laravel-one-of-many. Specifically, check out the User model.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.