Eloquent Custom Relations: HasOneOfMany &amp; Raw Joins | Mohamed Said        [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://msaied.com) [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles  ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

       [  ](https://github.com/EG-Mohamed)       

 [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

  [ home ](https://msaied.com)    [ articles ](https://msaied.com/articles)    Eloquent Custom Relations: Polymorphic Pivots, Has-One-Of-Many, and Raw Join Relations        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: Polymorphic Pivots, Has-One-Of-Many, and Raw Join Relations](https://cdn.msaied.com/728/b96439f5ef5f084b44d736951875f964.png)

  #laravel   #eloquent   #database   #orm   #php  

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

     2 Oct 2026      3 min read    ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)  Mohamed Said  

       Table of contents

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

 Found this useful?

          [  ](https://twitter.com/intent/tweet?url=https%3A%2F%2Fmsaied.com%2Farticles%2Feloquent-custom-relations-polymorphic-pivots-has-one-of-many-and-raw-join-relations&text=Eloquent+Custom+Relations%3A+Polymorphic+Pivots%2C+Has-One-Of-Many%2C+and+Raw+Join+Relations) [  ](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fmsaied.com%2Farticles%2Feloquent-custom-relations-polymorphic-pivots-has-one-of-many-and-raw-join-relations) 

 Frequently Asked Questions 
----------------------------

  3 questions  

     Q01  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. 

      Q02  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. 

      Q03  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. 

  Continue reading

 More Articles 
---------------

 [ View all    ](https://msaied.com/articles) 

 [ ![Laravel Caching Strategies: Tags, Stampede Prevention, and Cache-Aside at Scale](https://cdn.msaied.com/727/7873d7495db459e7a6e3bfbb8835852d.png) laravel caching redis 

### Laravel Caching Strategies: Tags, Stampede Prevention, and Cache-Aside at Scale

Beyond simple remember() calls: how to use cache tags for granular invalidation, prevent thundering-herd stamp...

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

 2 Oct 2026     3 min read  

  Read    

 ](https://msaied.com/articles/laravel-caching-strategies-tags-stampede-prevention-and-cache-aside-at-scale-2) [ ![Laravel AI SDK: Tool-Calling Agents and Conversation Persistence](https://cdn.msaied.com/726/cde0e4e03a15ea0776e82aca8727f660.png) laravel ai agents 

### Laravel AI SDK: Tool-Calling Agents and Conversation Persistence

Build reliable tool-calling AI agents in Laravel using the AI SDK, with typed tool definitions, structured res...

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

 1 Oct 2026     3 min read  

  Read    

 ](https://msaied.com/articles/laravel-ai-sdk-tool-calling-agents-and-conversation-persistence-4) [ ![Laravel 14 Adds a defaults() Method to Eloquent Models](https://cdn.msaied.com/725/6d4daa85070ffb81d6a9a3e25a8ed08c.png) Laravel 14 Eloquent Model Defaults 

### Laravel 14 Adds a defaults() Method to Eloquent Models

Laravel 14 introduces a defaults() method for Eloquent models, letting you set dynamic default attribute value...

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

 30 Sep 2026     3 min read  

  Read    

 ](https://msaied.com/articles/laravel-14-adds-a-defaults-method-to-eloquent-models) 

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

Explore

- [Home](https://msaied.com)
- [Projects](https://msaied.com/projects)
- [Articles](https://msaied.com/articles)
- [Certificates](https://msaied.com/certificates)
- [Contact](https://msaied.com#contact-section)

Connect

- [   hello@msaied.com ](mailto:hello@msaied.com)
- [   +20 109 461 9204 ](tel:+201094619204)

© 2026 Mohamed Said. All rights reserved.

 [  ](https://github.com/EG-Mohamed) [  ](https://www.linkedin.com/in/msaiedm/) [  ](https://wa.me/201094619204) [  ](mailto:hello@msaied.com) [  ](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
