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
Aug 16, 2020
6
Level 3
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
Please or to participate in this conversation.