Eloquent Custom Relations: HasOneOfMany &amp; Raw Joins | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. Eloquent Custom Relations: Polymorphic Pivots, Has-One-Of-Many, and Raw Join Relations

 Eloquent Custom Relations: Polymorphic Pivots, Has-One-Of-Many, and Raw Join Relations
=======================================================================================

 Beyond belongsTo and hasMany lies a set of underused Eloquent relation types that eliminate ugly query hacks. This article covers HasOneOfMany, custom intermediate table models, and rolling your own relation class.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 2 Oct 2026 · Updated 2 Oct 2026 · 3 min read

ShareCopy linkCopied

 ![Eloquent Custom Relations: Polymorphic Pivots, Has-One-Of-Many, and Raw Join Relations](https://cdn.msaied.com/728/b96439f5ef5f084b44d736951875f964.png) 

  On this page +1. [Eloquent Custom Relations: HasOneOfMany, Polymorphic Pivots, and Rolling Your Own](#eloquent-custom-relations-hasoneofmany-polymorphic-pivots-and-rolling-your-own)
2. [hasOne of Many: The Right Way to Fetch Latest/Oldest](#codehasonecode-of-many-the-right-way-to-fetch-latestoldest)
3. [Custom Pivot Models for Polymorphic Many-to-Many](#custom-pivot-models-for-polymorphic-many-to-many)
4. [Building a Bespoke Relation Class](#building-a-bespoke-relation-class)
5. [Takeaways](#takeaways)

 Eloquent Custom Relations: HasOneOfMany, Polymorphic Pivots, and Rolling Your Own
---------------------------------------------------------------------------------

Most Laravel codebases reach for `hasMany` + `sortByDesc` + `first()` when they need the *latest* related record. That pattern is fine until you need to eager-load it across 500 parent models. Eloquent ships with better tools — and when those run out, you can build your own relation class.

---

`hasOne` of Many: The Right Way to Fetch Latest/Oldest
------------------------------------------------------

Introduced in Laravel 8, `ofMany` variants let you declare a constrained single-record relation that Eloquent can eager-load efficiently.

```php
// User model
public function latestOrder(): HasOne
{
    return $this->hasOne(Order::class)->latestOfMany();
}

public function largestOrder(): HasOne
{
    return $this->hasOne(Order::class)->ofMany('total', 'max');
}

// Complex: latest order that is also paid
public function latestPaidOrder(): HasOne
{
    return $this->hasOne(Order::class)
        ->ofMany(
            ['created_at' => 'max'],
            fn ($q) => $q->where('status', 'paid')
        );
}

```

Under the hood Eloquent rewrites this as a self-join subquery, so `User::with('latestPaidOrder')->get()` fires **two** queries total — not N+1.

---

Custom Pivot Models for Polymorphic Many-to-Many
------------------------------------------------

When a polymorphic pivot carries extra columns, the default `MorphPivot` is often enough — but you lose casting, events, and custom methods unless you declare an explicit model.

```php
// Migration: taggables table with a weight column
Schema::create('taggables', function (Blueprint $table) {
    $table->foreignId('tag_id')->constrained();
    $table->morphs('taggable');
    $table->unsignedTinyInteger('weight')->default(1);
});

// Taggable pivot model
class Taggable extends MorphPivot
{
    protected $table = 'taggables';

    protected $casts = ['weight' => 'integer'];

    public function isPromoted(): bool
    {
        return $this->weight >= 5;
    }
}

// Tag model
public function posts(): MorphToMany
{
    return $this->morphedByMany(Post::class, 'taggable')
        ->using(Taggable::class)
        ->withPivot('weight');
}

```

Now `$tag->posts->first()->pivot->isPromoted()` works, and pivot observers fire correctly.

---

Building a Bespoke Relation Class
---------------------------------

Sometimes you need a relation that Eloquent simply does not model — for example, joining on a non-FK expression like `YEAR(orders.created_at) = users.cohort_year`.

Extend `Illuminate\Database\Eloquent\Relations\Relation` and implement the four required methods:

```php
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;

class HasManySameCohortYear extends Relation
{
    public function addConstraints(): void
    {
        if (static::$constraints) {
            $this->query->whereRaw(
                 'YEAR(orders.created_at) = ?',
                 [$this->parent->cohort_year]
            );
        }
    }

    public function addEagerConstraints(array $models): void
    {
        $years = collect($models)->pluck('cohort_year')->unique()->values();
        $this->query->whereRaw(
            'YEAR(orders.created_at) IN (' . $years->map(fn () => '?')->implode(',') . ')',
            $years->all()
        );
    }

    public function initRelation(array $models, $relation): array
    {
        foreach ($models as $model) {
            $model->setRelation($relation, $this->related->newCollection());
        }
        return $models;
    }

    public function match(array $models, Collection $results, $relation): array
    {
        foreach ($models as $model) {
            $matched = $results->filter(
                fn ($r) => (int) date('Y', strtotime($r->created_at)) === (int) $model->cohort_year
            );
            $model->setRelation($relation, $matched->values());
        }
        return $models;
    }

    public function getResults(): Collection
    {
        return $this->query->get();
    }
}

```

Then expose it from your model:

```php
public function cohortOrders(): HasManySameCohortYear
{
    return new HasManySameCohortYear(
        Order::query(),
        $this,
        'orders.created_at', // foreign key hint (unused here but required by constructor)
        'id'
    );
}

```

`User::with('cohortOrders')->get()` now runs two queries and maps correctly.

---

Takeaways
---------

- Use `ofMany` variants instead of `hasMany + collection manipulation` whenever you need a single constrained record — it eager-loads efficiently.
- Declare explicit `MorphPivot` subclasses when your polymorphic pivot carries domain logic or needs Eloquent events.
- Eloquent's `Relation` contract has only four abstract methods; implementing them gives you full eager-loading support for any join shape.
- Always implement `addEagerConstraints` with a `whereIn` — never loop and query inside `match`.

- [laravel](https://www.msaied.com/public/articles?search=laravel)
- [eloquent](https://www.msaied.com/public/articles?search=eloquent)
- [database](https://www.msaied.com/public/articles?search=database)
- [orm](https://www.msaied.com/public/articles?search=orm)
- [php](https://www.msaied.com/public/articles?search=php)

 Frequently asked questions 
---------------------------

  Does `latestOfMany` work with eager loading, or does it still cause N+1?It fully supports eager loading. Eloquent compiles it into a subquery join, so `Model::with('latestRelation')-&gt;get()` issues exactly two SQL queries regardless of result set size.

   When should I use a custom Relation class versus a scope or raw query?Use a custom Relation class when the association needs to be eager-loaded across collections, reused across multiple models, or composed with other Eloquent features like `withCount`. A scope is fine for single-model queries but cannot be eager-loaded.

   Can I attach pivot observers to a MorphPivot subclass?Yes. Register the observer in a service provider with `Taggable::observe(TaggableObserver::class)`. Events like `creating`, `updating`, and `deleting` fire as long as you use `attach`/`sync` with the `using()` declaration on the relation.

   ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)About the author
----------------

[Mohamed Said](https://www.msaied.com/public#person)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articleLaravel Caching Strategies: Tags, Stampede Prevention, and Cache-Aside at Scale](https://www.msaied.com/public/articles/laravel-caching-strategies-tags-stampede-prevention-and-cache-aside-at-scale-2) [Next articleLaravel Octane + FrankenPHP: Request Lifecycle, Shared State, and Safe Singleton Patterns](https://www.msaied.com/public/articles/laravel-octane-frankenphp-request-lifecycle-shared-state-and-safe-singleton-patterns)  

   On this page
-------------

1. [Eloquent Custom Relations: HasOneOfMany, Polymorphic Pivots, and Rolling Your Own](#eloquent-custom-relations-hasoneofmany-polymorphic-pivots-and-rolling-your-own)
2. [hasOne of Many: The Right Way to Fetch Latest/Oldest](#codehasonecode-of-many-the-right-way-to-fetch-latestoldest)
3. [Custom Pivot Models for Polymorphic Many-to-Many](#custom-pivot-models-for-polymorphic-many-to-many)
4. [Building a Bespoke Relation Class](#building-a-bespoke-relation-class)
5. [Takeaways](#takeaways)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
