Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

zack6849's avatar

Eager loading hasOne -- one query, but loads all models into memory?

Hi Guys!

I'm trying to eager load a model, in this case, specifically, I want to eager load the "latest" of a hasMany relationship, for example:

User class:

  public function posts(){
        return $this->hasMany(Post::class, 'author_id')
  }
    
  public function latestPost(){
      return $this->hasOne(Post::class, 'author_id')->latest();
  }

Controller:

  public function index(){
        $users = User::with('latestPost')->get();
        return view('welcome', compact('users'));
    }

result: one query for all the posts, which is great, except it hydrates 1400 models.

Source code for a minimum reproducible example

https://github.com/zack6849/eagerload-bug

Does anyone have any ideas on what the best approach here is?

I know @reinink has done some stuff with sub-selects for selecting a specific COLUMN, but i'm not sure what the best way is to load that MODEL

0 likes
6 replies
Sinnbeck's avatar

That code should only hydrate one post for each user (so 100 posts in total). Has one loads one for each. I will test the code when I get to a pc

zack6849's avatar

Right, but that's just a single column, I want the entire model, not just a single column, unfortunately.

Sinnbeck's avatar

What do you need it for? Perhaps I can help with a query for you

zack6849's avatar

I'm still sketching out requirements for this app, I can do a subquery, but if anyone smarter than me can find a way to eager load an entire model like that, it sure would make my life easier

Please or to participate in this conversation.