ORM N+1 query (ARCH7079)
Ce contenu n’est pas encore disponible dans votre langue.
Key php.performance.orm-n-plus-one · Severity error · Category performance
Looping over a query result and accessing a related model on each element runs a separate query per row (N+1). Eager load the relationship upfront.
Incorrect
Section titled “Incorrect”<?php$posts = Post::all();foreach ($posts as $post) { echo $post->author->name;}Correct
Section titled “Correct”<?php$posts = Post::with('author')->get();foreach ($posts as $post) { echo $post->author->name;}Eager load relationships accessed in the loop with with() to collapse them into one extra query.