Previously eager loaded relationship is queried again?

Posted 5 days ago by chrisebner

Hey all, I'm having an issue that is hard to explain. Using N+1 Query Detector I have a view that creates a Dashboardview that is nested.

Therefore I'm using eager-loading in the controller as such:

$abfrage = Abfrage::all(); // for examples sake, is more complex in real code

foreach ($abfragen as $abfrage) {
$x = Comparison::with([
                'abfrage',
                'consumption:id,amount',
                'rawratings'
                ])
                ->whereDate('created_at', Carbon::today())
                ->where(['abfrage_id' => $abfrage->id, ['position_self', '!=', null]])
                ->get()
                ->unique(['consumption_id']);
...

Then I need to modify the comparisons by manipulating some fields on them like so:

...
    foreach($x as $vergleich) {
    $vergleich->rawratingsDiscounted = $vergleich->rawratings->filter(function($item) {
                    return $item->discountNetSum > 0;
                });

    // ... abbreviated here for wall of text reasons.
    }
}
...

Then I push them onto an array that gets added as variable to the view.

In the blade template I also have a nested foreach loop that goes through the arrays and creates a matrix table like so:

$abfrage[0]->id | $vergleich[0] | $vergleich[1] | $vergleich[2] $abfrage[1]->id | $vergleich[0] | $vergleich[1] | $vergleich[2] etc...

The issue is now that in the view the N+1 Query Detector says:

Model: App\Comparison => Relation: App\Consumption - You should add with(App\Consumption) to eager-load this relation.

wherever i use dd($vergleich) i see the already loaded relation there. Any ideas?

Thanks <3

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.