Laravel Eloquent: how do I fix the N+1 query problem?

posée 3 months ago366 vuesen

6

My blog index page runs 101 queries for 100 posts because each post accesses $post->author->name. How do I reduce that?

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 3 months ago

1 réponse

7
✓
✓ Réponse acceptée

Eager load the relationship with with(). That's 2 queries instead of 101:

$posts = Post::with('author')->latest()->paginate(20);

Nested and constrained relations work too:

Post::with(['author:id,name', 'comments' => fn ($q) => $q->latest()->limit(3)])->get();

To catch this automatically in development, add this to AppServiceProvider::boot():

Model::preventLazyLoading(! app()->isProduction());

Lazy loading then throws an exception, so N+1s get fixed before they reach production. Laravel Debugbar or Telescope show the query count per page.

Connectez-vous pour dire si ça a marché.

answered 3 months ago

Sign in and verify your email to post an answer.