Replies: 2 comments 2 replies
-
Use morphMany with morphToMany-like trick (manual eager load) // Get all pivot IDs for this place // Preload all activities in one query // Attach activities to each pivot Now every pivot->activities is already loaded, no extra queries. Just 2 queries total: one for discounts, one for activities. |
Beta Was this translation helpful? Give feedback.
-
You’re running into the classic N+1 problem because each pivot model is loading its own activities separately inside the loop. You can solve this by eager loading the morph relation directly on the pivot models instead of calling load() inside map(). Here’s a cleaner approach:
Now each DiscountPlace pivot will have its activities relationship already loaded, and you’ll avoid the extra queries. You can access it like:
This way Laravel builds everything in as few queries as possible without any third-party packages. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I have this structure:
Now I have to load
activities
for each discount in a loop:As a result, I receive a lot of queries:
How can my task be done better without third-party libraries?
Beta Was this translation helpful? Give feedback.
All reactions