Spot icon indicating copy to clipboard operation
Spot copied to clipboard

Solve N+1 Query Problem

Open vlucas opened this issue 11 years ago • 8 comments

The classic N+1 query problem should be solved - specifically, for relations.

// Loop and print posts and comments
foreach($posts as $post) {
    echo "<h2>" . $post->title . "</h2>";
    echo "<p>" . $post->body . "</p>";
    echo "<hr />";
    // Comments
    foreach($post->comments as $comment) {
        echo "<p>" . $comment->body . "</p>";
    }
}

Currently, the above ‘HasMany’ example will incur N+1 queries. That is, one query will be executed for each set of comments requested for each post. So if 20 posts are returned and you print the comments for all posts, 20+1 queries will be executed.

This problem should be solved so that in the above situation, the maximum number of queries executed will be 2. One for all the posts, and one for all the comments related to all the posts in the result set. This would require some sort of intelligent cache of all the query conditions of the comments and all the primary keys of a collection once iteration begins.

vlucas avatar Nov 17 '12 22:11 vlucas