Eager Loading and Fetch Strategies
What you'll learn: How to load related data efficiently using join fetching, subselect fetching, and batch fetching to eliminate the N+1 query problem.
The Problem We're Solving
You've learned about the N+1 query problem (lesson 944): loading a list of objects, then making separate queries for each object's relationships. Eager loading is the solution—it tells your ORM to load related data upfront in fewer queries.
The Three Main Fetch Strategies
Join Fetching loads everything in a single query using SQL JOINs. When you load 100 orders with their customers, one query with a LEFT JOIN retrieves both orders and customers together. It's the most efficient approach when you know you'll need the related data immediately.
Subselect Fetching uses two queries: one for the main objects, then a second with a WHERE id IN (...) clause to fetch all related data at once. Loading those 100 orders would trigger: one query for orders, then one query fetching all 100 customers at once. Two round trips total, not 101.
Batch Fetching is a lazy loading optimization—it loads related data in chunks as accessed. If you access the first order's customer, the ORM loads customers for the next N orders (say, 10 at a time). It's a middle ground: you get 11 queries instead of 101, but only load what you actually touch.
Choosing Your Strategy
Use join fetching for one-to-one or small one-to-many relationships you always need. Use subselect fetching when join multiplication would create huge result sets. Use batch fetching when access patterns are unpredictable but you want protection against worst-case N+1.
Key Takeaway: Eager loading strategies—join fetching, subselect fetching, and batch fetching—preemptively load related data to replace hundreds of queries with just one, two, or a handful, dramatically improving performance.