Set up two relationships and load both. https://laravel.com/docs/9.x/eloquent-relationships#has-one-of-many
Oct 26, 2022
6
Level 2
Optimising Eloquent Query with Relationship
I have ~500 users whom each have a new metrics row added to the DB each day.
I was running a query to find the difference between a value from their first entry and their last.
I decided to eager load the relationship to cut down on DB calls.
Something like...
$users = User::with('metrics')->get();
foreach ($users as $user) {
$difference = $user->metrics->last()->value - $user->metrics->first()->value;
}
The problem with this approach is it loads all the user metrics models which is a drain on memory.
Is there a better approach to optimise the query?
Level 102
Please or to participate in this conversation.