# N+1 in Eloquent, ActiveRecord, Django, Prisma

> Spot and fix N+1 queries in Laravel Eloquent, Rails ActiveRecord, Django ORM and Prisma, with the slow code, the fix and the query log pattern.

Source: https://sqleye.com/blog/n-plus-one-in-eloquent-activerecord-django-prisma/ · Published: 2026-11-17 · Last updated: 2026-11-29 · Publisher: CodeROG (https://coderog.com)

To fix an N+1 query in an ORM, load the related rows up front instead of inside the loop: `with()` in Laravel, `includes` in Rails, `select_related` or `prefetch_related` in Django, `include` in Prisma. Each turns one query per row into one or two queries in total. The sections below show the slow pattern, the fix and what the query log looks like.

Versions checked against the official documentation: Laravel 12.x, Rails 8.1, Django 5.2, Prisma ORM 7. The SQL below is simplified; real statements differ in quoting and column lists.

## What does N+1 look like in a query log?

One query loads N parent rows, then the loop fires one query per parent. In a log, it is the same statement shape repeated with different values:

```sql
SELECT * FROM books;
SELECT * FROM authors WHERE id = 1;
SELECT * FROM authors WHERE id = 2;
SELECT * FROM authors WHERE id = 3;
-- ...one per book
```

After the fix, the repeats collapse into a single lookup, as in the Laravel example below. For the concept, see [What is an N+1 query?](/blog/what-is-an-n-plus-one-query/).

## How do I fix it in Laravel Eloquent?

Slow: relationships accessed as properties are lazy loaded by default.

```php
$books = Book::all();

foreach ($books as $book) {
    echo $book->author->name;
}
```

Fix with `with()`, or `load()` when the models are already fetched:

```php
$books = Book::with('author')->get();

// or, after the fact
$books = Book::all();
$books->load('author');
```

The log now shows two statements, for example `select * from books` and `select * from authors where id in (1, 2, 3, ...)`.

To catch regressions, call `Model::preventLazyLoading()` in the `boot` method of `AppServiceProvider`. It takes an optional boolean, so you can limit it to non-production environments:

```php
use Illuminate\Database\Eloquent\Model;

public function boot(): void
{
    Model::preventLazyLoading(! $this->app->isProduction());
}
```

A lazy load then throws `Illuminate\Database\LazyLoadingViolationException`. See [Connect Laravel](/docs/connect/laravel/) for pointing a Laravel app at a local database.

## How do I fix it in Rails ActiveRecord?

Slow:

```ruby
books = Book.limit(10)

books.each do |book|
  puts book.author.last_name
end
```

That is 1 query for the books plus 10 for the authors. Fix with `includes`, which the Rails guide recommends as the default:

```ruby
books = Book.includes(:author).limit(10)
```

| Method | Strategy | Conditions on the association |
|---|---|---|
| `includes` | Chooses between `preload` and `eager_load` | Yes |
| `preload` | One separate query per association | No |
| `eager_load` | A single `LEFT OUTER JOIN` | Yes |

For guard rails, `strict_loading` raises `ActiveRecord::StrictLoadingViolationError` when an association that was not loaded is accessed:

```ruby
user = User.strict_loading.first
user.address.city # raises ActiveRecord::StrictLoadingViolationError
```

It can also be set on one association (`has_many :books, strict_loading: true`). The `active_record.action_on_strict_loading_violation` setting can be `:log` to log instead of raising.

## How do I fix it in Django?

Slow:

```python
for entry in Entry.objects.all():
    print(entry.blog.name)  # one query per entry
```

For a `ForeignKey` or `OneToOneField`, use `select_related`, which does a SQL join in the one query:

```python
for entry in Entry.objects.select_related("blog"):
    print(entry.blog.name)  # no extra queries
```

For many-valued relations (many-to-many, reverse foreign key), use `prefetch_related`, which runs a separate lookup per relationship and joins the results in Python, usually with an `IN` query:

```python
pizzas = Pizza.objects.prefetch_related("toppings")
```

A gotcha from the Django docs: chaining a new filter, such as `pizza.toppings.filter(...)`, runs a fresh query and ignores the prefetched cache. In the log, a `select_related` fix shows one statement with a JOIN; a `prefetch_related` fix shows the main query plus one statement per relation.

## How do I fix it in Prisma?

Slow: one `findMany` per user in a loop.

```ts
const users = await prisma.user.findMany({});
for (const usr of users) {
  const posts = await prisma.post.findMany({ where: { authorId: usr.id } });
}
```

Fix with `include`, or with one `in` filter:

```ts
const usersWithPosts = await prisma.user.findMany({
  include: { posts: true },
});

const posts = await prisma.post.findMany({
  where: { authorId: { in: users.map((u) => u.id) } },
});
```

Both give two queries. Prisma's dataloader also batches `findUnique()` calls made in the same tick, so the docs suggest the fluent form `prisma.user.findUnique({ where: { id } }).posts()` to let the dataloader group them. The docs state it does not currently batch `findMany()`, so a `findMany` per row is still N+1. The number of SQL statements an `include` produces depends on the version and load strategy, so check your log rather than assuming.

## How SQLEye helps

SQLEye is unreleased and in development; there is no download yet. When released, its Live Eye feature flags a repeated query shape on one connection (by default 5 or more times within 1000 ms, with differing values) and collapses the burst into one expandable row showing the count. Repeating the identical statement with identical values is not flagged. That makes it a quick way to confirm an ORM fix works: run the page, look for the group, apply the fix, and see it disappear. Read about [N+1 detection](/docs/live-eye/n-plus-one/) and the [Laravel connection guide](/docs/connect/laravel/); Django, Rails and Node.js guides are under [Connect](/docs/connect/).
