Skip to content

ORM Pitfalls: N+1, Lazy Loading & Bulk Operations ​

"When accessing Eloquent relationships as properties, the related models are "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the "N + 1" query problem." — Laravel 13.x documentation, Eloquent: Relationships, "Eager Loading"

Summary: An ORM turns relationships into properties and writes into method calls, and every one of those hides SQL: the pitfalls are the statements you did not know were sent, the rows you did not know were loaded, and the rules (events, transactions, timestamps) a bulk call quietly skips. Focus: N+1 and eager loading, hydration cost, chunk vs chunkById vs lazy vs cursor, bulk insert/upsert/update, the transaction boundary, Active Record vs Data Mapper, raw SQL and injection, bad generated SQL, and how Eloquent, GORM, pgx, sqlx, sqlc, Ent, Bun and Doctrine differ. Learning goal: Read the SQL an ORM call will send, predict how many statements and how much memory a code path costs, and pick the right tool (model, query builder, raw SQL) per operation.

This page is the complete reference for the mistakes people make with an object-relational mapper (ORM) in production: the impedance mismatch that causes them, the N+1 query fan, eager loading in every form (with, load, loadMissing, withCount, withSum, nested eager loading, GORM Preload and Joins), lazy-loading guards (preventLazyLoading, shouldBeStrict), column selection and hydration cost, the four ways to walk a large table (chunk, chunkById, lazy, cursor), bulk writes (insert, upsert, insertOrIgnore, mass update vs per-row save) and the model events they skip, implicit transactions, the missing identity map, caching traps, raw SQL and injection, bad generated SQL, soft deletes, polymorphic relations, timestamps and time zones, optimistic locking, ORM-generated migrations, and how to read and test what the ORM sends. It does not re-teach neighbours: transactions are in ACID & Transactions and anomalies in Isolation Levels; the offset/keyset trade-off is in Pagination; version columns are in Optimistic vs Pessimistic Locking; reading plans is in Query Planning; index design is in Indexing; server-side cursors are in Cursors & Streaming; pool sizing is in Connection Pooling; migration safety is in Zero-Downtime Schema Migrations; injection in depth is in Database Security.

Page map ​

If you are looking forGo to
A table to memorise in a minuteEverything in one minute
Why ORMs hide cost, and the trade-offWhy ORM pitfalls exist
Fowler's vocabulary: Active Record, Data Mapper, Identity Map, Unit of Work, Lazy Load, RepositoryWhere the vocabulary comes from
One pitfall with a timeline and fixes in SQL, Go and LaravelThe pitfalls, one by one
Eloquent vs GORM vs pgx/sqlx/sqlc/Ent/Bun vs Doctrine/Hibernate/SQLAlchemy/Rails/DjangoPer-ORM behaviour
Reading the SQL, knobs, error messagesMechanics
Complete fixes: N+1, imports, sweeps, reports, testsSolving the classic problems
Which tool for which operationChoosing a tool
Monolith, microservices, replicas, scaleIn architecture
Reproduce N+1 and the chunk skipLab
Wrong beliefs, cheat sheet, termsMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The pitfalls. Every row is unpacked in the pitfalls section.

PitfallIn plain wordsTiny exampleThe fix
N+1 / lazy loadingOne query for the list, then one more per row25 books, $book->author in a loop = 26 querieswith('author'), Preload, a JOIN, withCount
Over-fetching and hydration costYou load whole objects when the page needs two columnsAuthor::all() to print namesselect(['id','name']), DTOs, pluck
Offset chunking while updatingThe loop shifts the pages under itselfchunk() + update on the filtered column skips rowschunkById, lazyById, keyset
Row-by-row writesN statements, N round trips, N commitssave() in a loop of 10,000insert, upsert, one transaction, COPY
Bulk call skips behaviourNo events, no observers, no casts, no updated_atBook::where(...)->update([...])Know the list; touch timestamps yourself
Implicit transactionOne write = one hidden transaction; a loop of writes is not atomic500 save() calls, crash at 300, 300 rows committedDB::transaction, db.Transaction
No identity mapThe same row loaded twice is two objectsBook::find(1) twice gives two instances; edits divergePass the object, or use a Data Mapper ORM
Raw SQL concatenationA string you built is a string an attacker can buildwhereRaw("name = '$name'")Bindings, ?, $1, whitelist identifiers
Bad generated SQLThe ORM is faithful, not clever5,000-element IN, 40-branch OR chain, whereHas on a large tableTemp table, ANY(array), join, rewrite
Soft deletes"Deleted" rows still exist, still count, still collideUnique email blocks re-signupPartial unique index, deleted_at in indexes
Polymorphic relationsOne column holds an id of different tablescommentable_id has no foreign keySeparate tables or accept and test the gap
Timestamps and time zonesDates are strings with hidden zone rulesnow() stored in app zone, read in anotherStore UTC, timestamptz, one source of truth
ORM-generated migrationsThe diff tool does not know your trafficRename column = drop + addReview --pretend SQL, expand/contract

The loaders. What each way of reading relations or rows costs.

MethodQueriesMemoryEager loadingSafe while updating filter columns
Lazy property access ($a->books)1 + Nsmall per stepnon/a
with('books') / Preload("Books")2whole result setyesn/a
Joins("Author") / JOIN FETCH1whole set, repeated parent columnsyesn/a
get() / Find1whole result setoptionaln/a
chunk(n)1 per page, OFFSETn modelsyesno
chunkById(n)1 per page, WHERE id >n modelsyesyes
lazy(n) / lazyById(n)like chunk / chunkByIdn models, flat iteratoryeslazyById yes
cursor()11 model, but the driver may buffernodepends on the driver

The bulk writers. What each one skips.

CallStatementsModel eventsCasts, mutatorscreated_at / updated_atAtomic
$model->save() per rowNfiredappliedseteach statement alone
Model::where(...)->update([...])1not firednot appliednot touchedyes (one statement)
Model::insert($rows)1 per batchnot firednot appliednot setper statement
Model::upsert($rows, ...)1 per batchnot firednot appliedupdated_at set on updateper statement
insertOrIgnore($rows)1 per batchnot firednot appliednot setper statement, hides errors
DB::table(...)->...1no model at allnonenot setper statement
GORM Create(&slice)1 per batchhooks runappliedset (autoCreateTime)wrapped in a transaction
pgx CopyFrom1 COPYnonenonenonewhole load or nothing

Why ORM pitfalls exist ​

A relational database stores sets of rows and answers set questions. An application stores graphs of objects and walks them one reference at a time. An ORM translates between the two, and the translation is where cost and surprises hide. The trade-off is always the same:

SideYou gainYou pay
Hide SQL behind objects (ORM)Less code, rich model behaviour, portability, fewer typosStatement count, memory and locks are no longer visible in the code
Write the SQL yourself (query builder, raw SQL, sqlc)Exact statements, exact columns, one-pass reportsMore code, hand-written mapping, you own the injection discipline
Load everything eagerlyFew round tripsBig result sets, repeated parent columns in joins, wasted memory
Load lazilySmall steps, simple codeA round trip per access, latency that grows with the data

An everyday picture. A warehouse. Sending a courier for one box at a time makes 300 trips for 300 boxes. A pick list lets the warehouse load one pallet and return once. Lazy loading is the courier who turns up each time you name the next box; eager loading is the pick list; bulk insert is the pallet. The warehouse manager (the database) is happy with either, but your delivery time (latency) is not.

Three common misunderstandings, up front ​

  1. "$book->author is a property read, so it is free." It looks like memory access and is a network round trip the first time.
  2. "The ORM is slow." Usually the ORM is faithful: it sent exactly the statements your code asked for, one per loop turn. The cost is in the access pattern, not the library.
  3. "Bulk methods are just faster save()." They are different operations: no model is loaded, so no events, casts, mutators, observers or automatic timestamps run.

The object-relational impedance mismatch Good to know ​

In plain words: Objects point at each other and hold collections; tables hold flat rows and relate by key. Converting between them is a translation problem, not a copy.

Common misunderstanding: "An ORM removes the mismatch." It only manages it; the differences stay and leak as N+1, identity issues, null handling and migration friction.

Definition: the set of conceptual differences between an in-memory object graph and a relational schema: identity (object reference vs primary key), relationships (pointers and collections vs foreign keys and joins), inheritance (class hierarchy vs tables), granularity (one rich object vs several rows), navigation (follow a pointer vs JOIN), and data types (language types vs column types, NULL, time zones). Martin Fowler puts it this way on his bliki: "The object/relational mapping problem is hard. Essentially what you are doing is synchronizing between two quite different representations of data, one in the relational database, and the other in-memory." He adds that it should by rights be called the "in-memory/relational mapping problem".

MismatchObject sideRelational sideWhere it bites
IdentityTwo references can be the same or different objectsOne primary key per rowNo identity map in Eloquent: two instances of one row
Relationships$author->books follows a pointerbooks.author_id joined by a queryN+1
Inheritanceclass Admin extends UserSingle table, table per class, or joined tablesWide nullable tables, hard queries
GranularityOne Address value objectSeveral columns, or a tableEmbedded vs related models
NavigationWalk the graphAsk a set questionLoops instead of joins
TypesDateTimeImmutable, enumstimestamptz, smallint, textTime zones, casting, enums as strings
WritesMutate in memory, save laterStatement per change, transaction boundarySilent partial writes

Where the vocabulary comes from ​

Most of the words used in this field (Active Record, Data Mapper, Identity Map, Unit of Work, Lazy Load, Repository) come from Martin Fowler's pattern catalogue for enterprise applications. The one-line definitions below are the catalogue's own wording:

PatternFowler's definition (verbatim)What it means in practice
Active Record"An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data."Eloquent, Rails, Django models: the object saves itself
Data Mapper"A layer of mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself."Doctrine, Hibernate, SQLAlchemy ORM, Ent: entities are plain, a mapper persists them
Identity Map"Ensures that each object gets loaded only once by keeping every loaded object in a map."Doctrine EntityManager, Hibernate session: the same row yields the same instance
Unit of Work"Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems."Doctrine flush(), Hibernate flush: changes are collected, then written together
Lazy Load"An object that doesn't contain all of the data you need but knows how to get it."Eloquent relation properties, Hibernate proxies
Repository"Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects."A class with find, add, remove that hides the query code

The term "N+1" itself I could not trace to an original source; the Laravel documentation names it and counts it, and I use its wording. The same goes for "impedance mismatch": I cite Fowler's description of the problem rather than a coinage. The Laravel 13.x docs count the cost for a 25-book list: "one query for the original book, and 25 additional queries to retrieve the author of each book", and show that a single with('author') means "only two queries will be executed". GORM documents the same remedy: "GORM allows eager loading relations in other SQL with Preload", and "Preload loads the association data in a separate query, Join Preload will loads association data using left join". Go libraries have no lazy loading to switch off, so a Go N+1 is a query you wrote inside a loop.

The pitfalls, one by one ​

All examples use this schema, which the lab creates: authors(id, name), books(id, author_id, sku unique, title, price_cents, in_stock, published_at, created_at, updated_at, deleted_at), comments(id, commentable_type, commentable_id, body). The snippet files Models.php, Lab.php, Bulk.php and Migration.php hold the Laravel side; the Go side is in the before, after, gorm, pgx and chunk packages.

N+1 and lazy loading Must-know ​

In plain words: You ask for a list, then for each item in the list you ask the database one more question. For 25 items that is 26 questions instead of 2.

Common misunderstanding: "N+1 only matters with thousands of rows." Each extra query costs a network round trip, a parse and a plan lookup, so 25 rows at 2 ms per trip already add 50 ms; at 200 rows per page and a loaded database it becomes the main latency. Also, "the database is fast, so it does not matter": the database is idle while your application waits for the next trip.

Definition: an access pattern where code issues one query to fetch N parent rows and then one query per parent to fetch a related row or collection, for 1 + N statements. Lazy loading is the mechanism: the relation is fetched when the property is first read.

Lazy loading: 1 + N round tripsApplicationforeach authorsQ1 SELECT * FROM authorsreturns 5 rowsQ2 ... WHERE author_id = 1Q3 ... WHERE author_id = 2Q4 ... WHERE author_id = 3Q5 ... WHERE author_id = 4Q6 ... WHERE author_id = 5Database6 parses, 6 tripsEager loading: Q1 SELECT * FROM authors, then Q2 SELECT * FROM books WHERE author_id IN (1,2,3,4,5). Always 2 queries, whatever N is.
text
     App (foreach authors)                        PostgreSQL
1    SELECT * FROM authors                        -- 5 rows
2    $a1->books  -> SELECT * FROM books WHERE author_id = 1
3    $a2->books  -> SELECT * FROM books WHERE author_id = 2
4    $a3->books  -> SELECT * FROM books WHERE author_id = 3
5    $a4->books  -> SELECT * FROM books WHERE author_id = 4
6    $a5->books  -> SELECT * FROM books WHERE author_id = 5
     -- 6 statements, 6 round trips. With 500 authors: 501.

Real scenarios: an admin list that prints each order's customer name (1 + 50); a Blade template calling $author->books->count() (hidden in the view); a JSON API resource that includes author and publisher (1 + 2N); a GraphQL resolver per field (the classic N+1 that DataLoader batches); a Go handler that calls GetAuthor(ctx, id) in a loop; a serializer that reads a relation the controller never loaded.

WhereHow the N+1 arisesVisible in code?
EloquentReading a relation property that is not loadedNo: looks like a field
GORMA db.Where(...).Find(...) inside a for loop; GORM has no lazy loadingYes: a query call in a loop
database/sql, pgx, sqlxSame: a query call in a loopYes
DoctrineTouching a lazy proxy or collectionNo
Hibernate / JPALazy @OneToMany or @ManyToOne(fetch=LAZY)No
SQLAlchemyDefault lazy="select"No
Rails ActiveRecordAssociation without includesNo
DjangoForeign key access without select_related / prefetch_relatedNo

Fix.

sql
-- the two statements eager loading sends
SELECT id, name FROM authors;
SELECT id, author_id, title FROM books WHERE author_id IN (1, 2, 3, 4, 5);
-- or one statement with a join (parent columns repeat on every book row)
SELECT a.id, a.name, b.id AS book_id, b.title
FROM authors a LEFT JOIN books b ON b.author_id = a.id;
-- or counting in SQL
SELECT a.id, a.name, count(b.id) AS books_count
FROM authors a LEFT JOIN books b ON b.author_id = a.id GROUP BY a.id;

Go: LoadBooksByAuthor sends one WHERE author_id = ANY(...); the code is in the after package.

go
// Package after loads and writes books in a fixed number of statements,
// no matter how many authors or rows there are.
package after

import (
	"context"
	"database/sql"
	"fmt"
	"strconv"
	"strings"
)

type Book struct {
	AuthorID int64
	Title    string
}

// LoadBooksByAuthor fetches the books of all the given authors in one query and
// groups them in memory. The ids are formatted as a comma-separated text value and
// turned into an array by string_to_array, so the driver needs no array support.
// Only integers are formatted here, so there is nothing to escape.
func LoadBooksByAuthor(ctx context.Context, db *sql.DB, authorIDs []int64) (map[int64][]string, error) {
	grouped := make(map[int64][]string, len(authorIDs))
	if len(authorIDs) == 0 {
		return grouped, nil
	}

	parts := make([]string, len(authorIDs))
	for i, id := range authorIDs {
		parts[i] = strconv.FormatInt(id, 10)
	}

	rows, err := db.QueryContext(ctx,
		`SELECT author_id, title FROM books
		 WHERE author_id = ANY(string_to_array($1, ',')::bigint[])
		 ORDER BY id`,
		strings.Join(parts, ","))
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var authorID int64
		var title string
		if err := rows.Scan(&authorID, &title); err != nil {
			return nil, err
		}
		grouped[authorID] = append(grouped[authorID], title)
	}
	return grouped, rows.Err()
}

// InsertBooks writes all books in one transaction using multi-row INSERT
// statements. Postgres allows at most 65535 bind parameters per statement, and
// each row uses two, so the rows go in batches of 1000 (2000 parameters).
func InsertBooks(ctx context.Context, db *sql.DB, books []Book) (err error) {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
			return
		}
		err = tx.Commit()
	}()

	const batchSize = 1000
	for start := 0; start < len(books); start += batchSize {
		end := min(start+batchSize, len(books))
		if err = insertBatch(ctx, tx, books[start:end]); err != nil {
			return err
		}
	}
	return nil
}

func insertBatch(ctx context.Context, tx *sql.Tx, books []Book) error {
	var sb strings.Builder
	sb.WriteString(`INSERT INTO books (author_id, title) VALUES `)
	args := make([]any, 0, len(books)*2)
	for i, b := range books {
		if i > 0 {
			sb.WriteString(", ")
		}
		fmt.Fprintf(&sb, "($%d, $%d)", 2*i+1, 2*i+2)
		args = append(args, b.AuthorID, b.Title)
	}
	_, err := tx.ExecContext(ctx, sb.String(), args...)
	return err
}

The "before" package is the same task done wrong: one query per author, written by hand.

go
// Package before shows the habits an ORM hides, written by hand with
// database/sql: one query per parent row, and one statement per inserted row.
package before

import (
	"context"
	"database/sql"
)

type Book struct {
	AuthorID int64
	Title    string
}

// AuthorTitles returns the book titles for every author.
// It runs one query for the authors and then one more per author: 1 + N round trips.
func AuthorTitles(ctx context.Context, db *sql.DB) (map[string][]string, error) {
	rows, err := db.QueryContext(ctx, `SELECT id, name FROM authors ORDER BY id`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	result := make(map[string][]string)
	for rows.Next() {
		var id int64
		var name string
		if err := rows.Scan(&id, &name); err != nil {
			return nil, err
		}
		titles, err := titlesFor(ctx, db, id) // one extra query per author
		if err != nil {
			return nil, err
		}
		result[name] = titles
	}
	return result, rows.Err()
}

func titlesFor(ctx context.Context, db *sql.DB, authorID int64) ([]string, error) {
	rows, err := db.QueryContext(ctx, `SELECT title FROM books WHERE author_id = $1`, authorID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var titles []string
	for rows.Next() {
		var title string
		if err := rows.Scan(&title); err != nil {
			return nil, err
		}
		titles = append(titles, title)
	}
	return titles, rows.Err()
}

// SaveBooks inserts one row per statement. Outside an explicit transaction each
// Exec commits on its own, so 10,000 rows mean 10,000 commits and round trips.
func SaveBooks(ctx context.Context, db *sql.DB, books []Book) error {
	for _, b := range books {
		if _, err := db.ExecContext(ctx,
			`INSERT INTO books (author_id, title) VALUES ($1, $2)`, b.AuthorID, b.Title); err != nil {
			return err
		}
	}
	return nil
}

The Eloquent "before" is the same N+1 plus the habits that follow it:

php
<?php

// Before: the habits that turn ORM code into N+1 queries, row-by-row writes,
// and chunks that skip rows.

namespace App\Http\Controllers;

use App\Models\Author;
use App\Models\Book;

final class AuthorIndexController
{
    // N+1: one query for the authors, then one more per author when the loop
    // reads $author->books. A Blade template written the same way,
    //   @foreach ($authors as $author) {{ $author->books->count() }} @endforeach
    // hides the same cost.
    public function index(): array
    {
        $rows = [];

        foreach (Author::all() as $author) {
            $rows[] = [
                'name' => $author->name,
                'books' => $author->books->count(),
            ];
        }

        return $rows;
    }
}

final class BookImporter
{
    // 10,000 rows mean 10,000 INSERT statements. Each save() is its own
    // statement, and nothing groups them into one transaction.
    public function import(array $rows): void
    {
        foreach ($rows as $row) {
            $book = new Book();
            $book->author_id = $row['author_id'];
            $book->sku = $row['sku'];
            $book->title = $row['title'];
            $book->price_cents = $row['price_cents'];
            $book->save();
        }
    }

    // chunk() pages with OFFSET. Each update removes the row from the
    // "in_stock = true" filter, so the next page skips rows that were never visited.
    public function markOutOfStock(): void
    {
        Book::where('in_stock', true)->chunk(200, function ($books) {
            $books->each->update(['in_stock' => false]);
        });
    }
}

Laravel: with runs the second query, withCount computes the number in SQL.

php
<?php

// After: select what the view needs, count in SQL, write in batches, and
// page by id when the rows you page over are also the rows you update.

namespace App\Http\Controllers;

use App\Models\Author;
use App\Models\Book;

final class AuthorIndexController
{
    // withCount() adds a books_count column computed by one subquery, so the view
    // never touches the books table. Only the columns it needs are selected.
    // Include the id when you select columns, or the relation cannot be matched.
    public function index(): array
    {
        return Author::query()
            ->select(['id', 'name'])
            ->withCount('books')
            ->orderBy('id')
            ->get()
            ->map(fn (Author $author) => [
                'name' => $author->name,
                'books' => $author->books_count,
            ])
            ->all();
    }

    // When the list needs the related rows themselves, eager load them in one
    // extra query: with('books:id,author_id,title') instead of a loop of queries.
    public function withTitles(): array
    {
        return Author::query()
            ->select(['id', 'name'])
            ->with('books:id,author_id,title')
            ->orderBy('id')
            ->get()
            ->all();
    }
}

final class BookImporter
{
    // upsert() sends each batch as one INSERT ... ON CONFLICT statement.
    // uniqueBy names the unique index that decides "already exists".
    public function import(array $rows): void
    {
        foreach (array_chunk($rows, 500) as $batch) {
            Book::upsert(
                $batch,
                uniqueBy: ['sku'],
                update: ['title', 'price_cents'],
            );
        }
    }

    // lazyById() pages by primary key, so rows that leave the filter after the
    // update do not shift the next page.
    public function markOutOfStock(): void
    {
        Book::where('in_stock', true)
            ->lazyById(200, column: 'id')
            ->each->update(['in_stock' => false]);
    }
}

Eager loading: with, load, loadMissing, withCount, withSum Must-know ​

In plain words: Tell the ORM up front which related data you need, and it fetches all of it in a fixed number of queries.

Common misunderstanding: "Eager loading is always faster." It trades round trips for memory and for the cost of building and matching the result set. Eager-loading a million parents with every relation can be slower than the N+1 it replaced. Also: "with makes a JOIN." In Eloquent it does not; it runs a second query with WHERE fk IN (...) and stitches the results in PHP.

Definition: loading related models in advance, in one query per relation, rather than on first property access.

Eloquent callWhenWhat it sends
Author::with('books')->get()Before the parents are fetchedParent query, then books WHERE author_id IN (...)
$authors->load('books')After you already have the modelsSame second query, on the existing collection
$author->loadMissing('books')You are unsure if it is loadedLoads only relations not yet present
Author::withCount('books')You need only a numberA correlated subquery; adds books_count
Author::withSum('books', 'price_cents')A sum, min, max, avg or existsAdds books_sum_price_cents; also withMin, withMax, withAvg, withExists
with('books:id,author_id,title')You need only some columnsNarrow select; keep the key and foreign key
with(['books' => fn ($q) => $q->where('in_stock', true)])You need a constrained relationExtra WHERE on the second query
Author::withWhereHas('books', fn ($q) => ...)Filter parents by children and load the matchesEXISTS filter plus eager load
Model::automaticallyEagerLoadRelationships()You want the framework to batch for youLoads the relation for all siblings on first access
protected $with = ['author']A relation is always neededEager loads on every query; without('author') opts out

The Laravel docs require that when you narrow a relation's columns you keep the id and foreign key columns, or the matching of children to parents fails. The same page documents withSum, withMin, withMax, withAvg and withExists as siblings of withCount, and says the result lands in a {relation}_{function}_{column} attribute.

text
     Eloquent Author::with('books:id,author_id,title')->get()
1    select * from authors
2    select id, author_id, title from books where books.author_id in (1, 2, 3, 4, 5)
3    -- PHP groups the books by author_id and sets each author's relation

Nested eager loading uses dot notation: Author::with('books.comments.user') loads three more queries, one per level; with('books.comments:id,commentable_id,body') narrows the leaf. The depth multiplies rows: 100 authors × 20 books × 30 comments is 60,000 comment models in memory. Model::automaticallyEagerLoadRelationships() (Laravel docs, "Automatic Eager Loading") loads a relation for every model in the same collection the first time one of them reads it, which turns the nested loop above into one query per level without writing with; it still loads every column.

GORM:

go
// two queries: users, then orders WHERE user_id IN (...)
db.Preload("Orders").Find(&users)
// nested and constrained
db.Preload("Orders.OrderItems.Product").Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
// one query with LEFT JOIN (belongs-to and has-one)
db.Joins("Company").Joins("Manager").Find(&users)
// every association (only one level)
db.Preload(clause.Associations).Find(&users)

The three Go ORM shapes, side by side, are in the gorm snippet, which counts queries with a callback and prints the SQL with ToSQL:

go
// Command gorm reproduces an N+1 with GORM, counts the queries, and fixes it
// with Preload and Joins. It needs a PostgreSQL database with the authors and
// books tables from the lab; it exits early when DATABASE_URL is not set.
package main

import (
	"fmt"
	"os"
	"sync/atomic"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

type Author struct {
	ID    uint
	Name  string
	Books []Book
}

type Book struct {
	ID       uint
	AuthorID uint
	Title    string
	Author   Author
}

func main() {
	dsn := os.Getenv("DATABASE_URL")
	if dsn == "" {
		fmt.Println("set DATABASE_URL, for example postgres://postgres:pg@localhost:5432/lab")
		return
	}
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("open:", err)
		return
	}

	// A callback after every query makes the statement count measurable.
	var queries atomic.Int64
	err = db.Callback().Query().After("gorm:query").Register("lab:count", func(*gorm.DB) {
		queries.Add(1)
	})
	if err != nil {
		fmt.Println("callback:", err)
		return
	}

	measure := func(name string, run func() error) {
		queries.Store(0)
		if err := run(); err != nil {
			fmt.Println(name, "error:", err)
			return
		}
		fmt.Printf("%-12s %d queries\n", name, queries.Load())
	}

	measure("n+1", func() error { return nPlusOne(db) })
	measure("preload", func() error { return preload(db) })
	measure("joins", func() error { return joins(db) })

	// ToSQL renders the statement without running it, so the SQL can be read.
	sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
		return tx.Joins("Author").Find(&[]Book{})
	})
	fmt.Println(sql)
}

// nPlusOne is the classic mistake: one query for the authors and one per author.
func nPlusOne(db *gorm.DB) error {
	var authors []Author
	if err := db.Find(&authors).Error; err != nil {
		return err
	}
	for i := range authors {
		err := db.Where("author_id = ?", authors[i].ID).Find(&authors[i].Books).Error
		if err != nil {
			return err
		}
	}
	return nil
}

// preload runs two queries: authors, then books WHERE author_id IN (...).
func preload(db *gorm.DB) error {
	var authors []Author
	return db.Preload("Books").Find(&authors).Error
}

// joins runs one query with a LEFT JOIN. It suits belongs-to and has-one
// associations; a has-many association is loaded with Preload instead.
func joins(db *gorm.DB) error {
	var books []Book
	return db.Joins("Author").Find(&books).Error
}
Lazy: query on first property accessQuery parentsLoop row iRead $a->booksLoaded?no: run queryUse rowsnext rowrepeat for every parent row: N extra round tripsEager: with(), Preload, selectinloadQuery parents1 queryCollect ids[1,2,3,...]Query childrenWHERE fk IN (...)Stitch in memorygroup by fkLoop row ino queryCost model: lazy = 1 + N round trips, small memory per step. Eager = 2 round trips, whole result set in memory.JOIN-based loading (GORM Joins, JOIN FETCH) is a third shape: 1 query, but parent columns repeat on every child row.

Real scenarios: a dashboard of customers with order counts (withCount); an invoice list with line items and tax (nested with); a feed with author and last comment (constrained with plus Joins); a export that needs only id and email.

Preload or join?

ApproachQueriesDuplicates parent columnsGood forLimit
Separate query (with, Preload, selectinload)1 per relationnohas-many, deep graphsIN list grows with parents
JOIN (Joins, joinedload, JOIN FETCH)1yesbelongs-to, has-one, filters on the childhas-many multiplies rows, breaks LIMIT on the parent
Subquery count (withCount)1nonumbers onlyone correlated subquery per count

Strictness: preventLazyLoading and shouldBeStrict Important ​

In plain words: Make the program fail loudly in development when it lazy loads, so a missed with() is a failing test, not a slow page.

Common misunderstanding: "Turning it on in production will make the app safer." It makes the app throw on pages that work today. Turn it on outside production, or log in production.

Definition: Model::preventLazyLoading() makes lazy loading throw Illuminate\Database\LazyLoadingViolationException. Model::handleLazyLoadingViolationUsing(fn) replaces the throw with your handler. Model::shouldBeStrict() enables three checks together: preventLazyLoading, preventSilentlyDiscardingAttributes and preventAccessingMissingAttributes (read in the 13.x Model.php source; the docs page describes the first two separately and does not mention shouldBeStrict).

php
<?php

namespace App\Providers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;

final class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Turns on lazy-loading, silently-discarded-attribute and missing-attribute
        // checks. Enabled outside production so mistakes fail in development.
        Model::shouldBeStrict(! $this->app->isProduction());
    }
}
CheckThrows whenException
preventLazyLoadingA relation is lazy loadedLazyLoadingViolationException
preventSilentlyDiscardingAttributesfill() / create() gets a key not in $fillableMassAssignmentException
preventAccessingMissingAttributesYou read an attribute that was not selected or does not existMissingAttributeException
EnvironmentRecommended settingWhy
Local, CIshouldBeStrict()N+1 becomes a red test
StagingshouldBeStrict() with real data volumeSees the shapes production sees
ProductionpreventLazyLoading() with handleLazyLoadingViolationUsing loggingVisibility without outages

In Go there is nothing to prevent; the equivalent is a query counter in tests (see Testing) and go vet-level review: a query call inside for.

Selecting columns and hydration cost Important ​

In plain words: Every row you load becomes an object with all its columns, casts and relations. A page that needs a name pays for the whole row.

Common misunderstanding: "The cost is the SQL." For wide tables the cost is often PHP or Go: reading the bytes, building objects, running casts and mutators, and the memory they hold.

Definition: hydration is converting result rows into model objects (allocating, setting attributes, applying casts, tracking original values for dirty checking). The cost grows with rows × columns × features (casts, accessors, observers).

Read shapeCostUse when
Book::all()All columns, one model per row, dirty trackingRarely
Book::select(['id','title'])->get()Fewer bytes, still modelsYou need models but few columns
DB::table('books')->get()stdClass rows, no casts, no eventsRead-only lists
Book::pluck('title', 'id')An array, no modelsDropdowns, id lists
Book::toBase()->get()Query builder rows from an Eloquent queryKeep scopes, skip hydration
Book::query()->value('title') / exists() / count()One scalarPresence and counts
GORM Select("id", "title").Find(&dtos) into a small structFewer columns, no modelRead-only lists
sqlc generated row structExactly the selected columnsTyped reads
text
     Peak memory, 100,000 books, 12 columns (illustrative ratios, measure your own)
1    Book::all()                       -> hundreds of MB of PHP objects
2    Book::select(['id','title'])      -> a fraction of that
3    DB::table('books')->pluck('title')-> a flat array of strings
4    cursor() / lazy() / chunkById     -> constant: one page or one model at a time

Real scenarios: a CSV export that loads User::all() and runs out of memory (Allowed memory size of 134217728 bytes exhausted); an API that returns only id and name but selects 40 columns including a jsonb blob; a list page that loads a TEXT column holding rendered HTML. Selecting columns also lets PostgreSQL use an index-only scan (see Indexing) and avoid fetching TOASTed values.

sql
-- the wide read
SELECT * FROM books WHERE author_id = 7;
-- the narrow read that an index on (author_id) INCLUDE (title) can answer
SELECT id, title FROM books WHERE author_id = 7;

Walking a big table: chunk, chunkById, lazy, cursor Must-know ​

In plain words: When a table is too big to load at once you read it in slices. How you choose the next slice decides whether you miss rows.

Common misunderstanding: "chunk is the safe default for batch updates." It is safe only if the loop does not change the rows that match the filter. Laravel's own docs warn that using chunk on a column you also update "could lead to unexpected and inconsistent results".

Definition: chunk(n, fn) runs ORDER BY id LIMIT n OFFSET k for k = 0, n, 2n, ...; chunkById(n, fn) runs WHERE id > last ORDER BY id LIMIT n; lazy(n) is chunk flattened into a LazyCollection; lazyById(n) is chunkById flattened; cursor() runs one query and yields one model at a time with a PHP generator. (In the 13.x source chunk pages with forPage, which is offset/limit.)

text
     chunk(2) with an update that removes rows from the filter  (WHERE in_stock = true, rows 1..6)
1    page 1: OFFSET 0 LIMIT 2  -> rows 1, 2    update -> in_stock = false
2    page 2: OFFSET 2 LIMIT 2  -> rows 5, 6    (rows 3, 4 moved to offsets 0 and 1)
3    page 3: OFFSET 4 LIMIT 2  -> (empty)
     -- rows 3 and 4 were never visited, no error.

     chunkById(2): WHERE id > last
1    page 1: id > 0 LIMIT 2    -> rows 1, 2    update
2    page 2: id > 2 LIMIT 2    -> rows 3, 4    update
3    page 3: id > 4 LIMIT 2    -> rows 5, 6    update
4    page 4: id > 6 LIMIT 2    -> empty, done
MethodPagingMemoryEager loadingSafe when updating the filterNotes
chunkOFFSETn modelsyesnoOffset also gets slower deep into the table
chunkByIdWHERE id >n modelsyesyesNeeds a unique, ordered key; adds its own where, so group your own conditions in a closure
lazyOFFSETn models, iteratoryesnochunk with a flat API
lazyByIdWHERE id >n models, iteratoryesyeslazyByIdDesc for descending
cursorone query1 modelnodependsThe Laravel docs say it "cannot eager load relationships"; PDO may still buffer all rows, so it "will still eventually run out of memory"
eachchunkn modelsyesnoeach(fn) on the builder is chunk-then-foreach
GORM FindInBatcheskeyset by primary keyn structsPreload worksyesPages by primary key
database/sql Rowsone query1 rown/adependsNeeds a transaction or cursor for stable reads; see Cursors & Streaming

Real scenarios: flipping in_stock = false for a supplier's catalogue (the example above); re-indexing documents into a search engine; sending a notification to every user who has a pending invoice; deleting soft-deleted rows older than a year.

The Go equivalent shows both shapes and is the lab's second experiment:

go
// Package chunk contrasts offset paging with keyset paging while the loop
// changes the rows it is reading, the Go version of chunk vs chunkById.
package chunk

import (
	"context"
	"database/sql"
)

// OffsetSweep marks books out of stock page by page using OFFSET. Every update
// removes the row from the in_stock = true filter, so the next OFFSET skips
// rows that were never visited. It is the shape of Eloquent's chunk().
func OffsetSweep(ctx context.Context, db *sql.DB, size int) (int, error) {
	visited := 0
	for offset := 0; ; offset += size {
		ids, err := pageByOffset(ctx, db, size, offset)
		if err != nil {
			return visited, err
		}
		if len(ids) == 0 {
			return visited, nil
		}
		for _, id := range ids {
			if _, err := db.ExecContext(ctx, `UPDATE books SET in_stock = false WHERE id = $1`, id); err != nil {
				return visited, err
			}
			visited++
		}
	}
}

func pageByOffset(ctx context.Context, db *sql.DB, size, offset int) ([]int64, error) {
	return scanIDs(ctx, db,
		`SELECT id FROM books WHERE in_stock ORDER BY id LIMIT $1 OFFSET $2`, size, offset)
}

// KeysetSweep does the same work with WHERE id > last. The position is a key
// value, not a row count, so rows leaving the filter cannot shift the page.
// It is the shape of Eloquent's chunkById().
func KeysetSweep(ctx context.Context, db *sql.DB, size int) (int, error) {
	visited := 0
	var last int64
	for {
		ids, err := scanIDs(ctx, db,
			`SELECT id FROM books WHERE in_stock AND id > $1 ORDER BY id LIMIT $2`, last, size)
		if err != nil {
			return visited, err
		}
		if len(ids) == 0 {
			return visited, nil
		}
		for _, id := range ids {
			if _, err := db.ExecContext(ctx, `UPDATE books SET in_stock = false WHERE id = $1`, id); err != nil {
				return visited, err
			}
			visited++
		}
		last = ids[len(ids)-1]
	}
}

func scanIDs(ctx context.Context, db *sql.DB, query string, args ...any) ([]int64, error) {
	rows, err := db.QueryContext(ctx, query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var ids []int64
	for rows.Next() {
		var id int64
		if err := rows.Scan(&id); err != nil {
			return nil, err
		}
		ids = append(ids, id)
	}
	return ids, rows.Err()
}
sql
-- offset page k (what chunk sends)
SELECT * FROM books WHERE in_stock = true ORDER BY id LIMIT 200 OFFSET 400;
-- keyset page (what chunkById sends); needs an index on id (the primary key is enough)
SELECT * FROM books WHERE in_stock = true AND id > 612 ORDER BY id LIMIT 200;

For the offset-versus-keyset cost model, see Pagination: Offset vs Keyset. For cursor() and the way PDO buffers rows, see Cursors & Streaming: on PostgreSQL a PHP pdo_pgsql result is fetched whole by default, so cursor() saves model objects but not driver memory.

Bulk writes: insert, upsert, insertOrIgnore, mass update Must-know ​

In plain words: Send many rows in one statement instead of many statements. It is much faster and it skips the per-row behaviour you may be relying on.

Common misunderstanding: "upsert is a better save()." It writes SQL directly: no model is loaded, so events, observers, casts and mutators do not run, and it needs a unique index on the conflict columns.

Definition: a bulk write is one statement that affects many rows (INSERT ... VALUES (...), (...), INSERT ... ON CONFLICT, UPDATE ... WHERE, COPY). A mass update means an UPDATE through the query builder; a per-row save loads each model, mutates it and writes it.

text
     Importing 10,000 rows
     Row-by-row save()                        Batched
1    10,000 INSERT statements                 20 INSERT statements of 500 rows
2    10,000 round trips                       20 round trips
3    10,000 implicit transactions (commits)   1 explicit transaction (1 commit)
4    10,000 WAL flushes (fsync each)          1 WAL flush
5    ~ tens of seconds                        ~ hundreds of milliseconds
OperationEloquentGORMpgx / SQLEvents skipped
Insert manyBook::insert($rows)db.Create(&slice) (single statement; hooks still run) / CreateInBatches(rows, 100)multi-row VALUES, unnest, CopyFromEloquent: yes; GORM: no
Insert, ignore duplicatesinsertOrIgnore($rows)Clauses(clause.OnConflict{DoNothing: true})ON CONFLICT DO NOTHINGEloquent: yes
Insert or updateBook::upsert($rows, ['sku'], ['title'])Clauses(clause.OnConflict{UpdateAll: true})ON CONFLICT (sku) DO UPDATE / MySQL ON DUPLICATE KEY UPDATEEloquent: yes
Update manyBook::where(...)->update([...])db.Model(&Book{}).Where(...).Updates(...)UPDATE ... WHEREEloquent: yes
Delete manyBook::where(...)->delete()db.Where(...).Delete(&Book{})DELETE ... WHEREEloquent: yes
Bulk loadinsertUsing, raw COPYCopyFrom via pgxCOPY books FROM STDINn/a
Per-row$book->save()db.Save(&book)UPDATE ... WHERE idno

insertOrIgnore deserves care. The Laravel docs say it "will ignore errors while inserting records", that duplicate-key errors are ignored and "other types of errors may also be ignored depending on the database engine", and that it bypasses MySQL's strict mode. On PostgreSQL it emits ON CONFLICT DO NOTHING, which only ignores unique-key conflicts. upsert is described in the Laravel docs as "a single, atomic operation"; all databases except SQL Server need a primary or unique index on the conflict columns, and MySQL and MariaDB ignore the argument and use their own keys.

Parameter limits. PostgreSQL's wire protocol carries at most 65,535 bind parameters in one statement (a 16-bit count), MySQL prepared statements cap at 65,535 placeholders (error 1390: "Prepared statement contains too many placeholders"), and SQLite's SQLITE_MAX_VARIABLE_NUMBER defaults to 32,766 from 3.32. A multi-row insert uses rows × columns parameters, so batch: 1,000 rows of 3 columns is 3,000 parameters. unnest with arrays (the pgx snippet) keeps the count at the number of columns.

go
// Command pgx shows the no-ORM patterns: one query for many parents, a
// pgx.Batch for many statements in one round trip, a multi-row upsert, and
// COPY for bulk loads. It exits early when DATABASE_URL is not set.
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/jackc/pgx/v5"
)

type Book struct {
	ID       int64  `db:"id"`
	AuthorID int64  `db:"author_id"`
	Title    string `db:"title"`
}

func main() {
	dsn := os.Getenv("DATABASE_URL")
	if dsn == "" {
		fmt.Println("set DATABASE_URL, for example postgres://postgres:pg@localhost:5432/lab")
		return
	}
	ctx := context.Background()
	conn, err := pgx.Connect(ctx, dsn)
	if err != nil {
		fmt.Println("connect:", err)
		return
	}
	defer conn.Close(ctx)

	books, err := BooksByAuthors(ctx, conn, []int64{1, 2, 3})
	if err != nil {
		fmt.Println("query:", err)
		return
	}
	fmt.Println("books:", len(books))
}

// BooksByAuthors fetches the books of many authors in one statement. pgx
// encodes a []int64 as a PostgreSQL array, so ANY($1) needs no string tricks.
func BooksByAuthors(ctx context.Context, conn *pgx.Conn, ids []int64) ([]Book, error) {
	rows, err := conn.Query(ctx,
		`SELECT id, author_id, title FROM books WHERE author_id = ANY($1) ORDER BY id`, ids)
	if err != nil {
		return nil, err
	}
	return pgx.CollectRows(rows, pgx.RowToStructByName[Book])
}

// RenameMany queues many UPDATE statements and sends them in one round trip.
// Statements still run one by one on the server; only the network trips shrink.
func RenameMany(ctx context.Context, conn *pgx.Conn, titles map[int64]string) error {
	batch := &pgx.Batch{}
	for id, title := range titles {
		batch.Queue(`UPDATE books SET title = $1 WHERE id = $2`, title, id)
	}
	results := conn.SendBatch(ctx, batch)
	defer results.Close()
	for range titles {
		if _, err := results.Exec(); err != nil {
			return err
		}
	}
	return results.Close()
}

// UpsertBooks writes many rows with one statement using unnest, so the number
// of bind parameters stays at three however many rows there are.
func UpsertBooks(ctx context.Context, conn *pgx.Conn, skus []string, authorIDs []int64, titles []string) error {
	_, err := conn.Exec(ctx,
		`INSERT INTO books (sku, author_id, title)
		 SELECT * FROM unnest($1::text[], $2::bigint[], $3::text[])
		 ON CONFLICT (sku) DO UPDATE SET title = EXCLUDED.title`,
		skus, authorIDs, titles)
	return err
}

// CopyBooks loads rows through the COPY protocol, the fastest path in pgx.
// COPY has no ON CONFLICT: a duplicate key fails the whole load.
func CopyBooks(ctx context.Context, conn *pgx.Conn, rows [][]any) (int64, error) {
	return conn.CopyFrom(ctx,
		pgx.Identifier{"books"},
		[]string{"sku", "author_id", "title"},
		pgx.CopyFromRows(rows))
}
php
<?php

// Bulk writes and what they skip: events, casts, mutators, timestamps.

namespace App\Services;

use App\Models\Book;
use Illuminate\Support\Facades\DB;

final class BulkWrites
{
    /**
     * Mass update: one UPDATE statement. The saving/saved/updating/updated
     * model events do not fire and no model is loaded. updated_at is NOT touched
     * unless you set it yourself.
     */
    public function discount(int $authorId): int
    {
        return Book::where('author_id', $authorId)->update([
            'price_cents' => DB::raw('price_cents * 9 / 10'),
            'updated_at' => now(),
        ]);
    }

    /** Per-row save: N SELECT-then-UPDATE round trips, events fire, one wrapper transaction. */
    public function discountEach(int $authorId): void
    {
        DB::transaction(function () use ($authorId) {
            Book::where('author_id', $authorId)->each(function (Book $book) {
                $book->price_cents = intdiv($book->price_cents * 9, 10);
                $book->save();
            });
        });
    }

    /**
     * insert(): one multi-row INSERT, no events, no timestamps, no casts.
     * Batch to stay under the driver's bind-parameter limit (65535 for
     * PostgreSQL and MySQL prepared statements).
     */
    public function insertMany(array $rows): void
    {
        $now = now();
        foreach (array_chunk($rows, 1000) as $batch) {
            Book::insert(array_map(fn ($r) => $r + ['created_at' => $now, 'updated_at' => $now], $batch));
        }
    }

    /** insertOrIgnore() swallows duplicate-key errors, and on MySQL other errors too. */
    public function insertIgnoring(array $rows): int
    {
        return DB::table('books')->insertOrIgnore($rows);
    }

    /** upsert(): INSERT ... ON CONFLICT DO UPDATE (PostgreSQL) / ON DUPLICATE KEY UPDATE (MySQL). */
    public function sync(array $rows): int
    {
        return Book::upsert($rows, uniqueBy: ['sku'], update: ['title', 'price_cents']);
    }

    /** A large IN list: whereIntegerInRaw inlines integers instead of binding them. */
    public function find(array $ids)
    {
        return Book::whereIntegerInRaw('id', $ids)->get();
    }

    /** Raw SQL done safely: values travel as bindings, never inside the string. */
    public function search(string $term): array
    {
        return DB::select('SELECT id, title FROM books WHERE title ILIKE ? LIMIT 20', ["%{$term}%"]);
    }

    /** Silent-save: keeps events off for one model, for importers that must not notify. */
    public function importOne(array $attributes): Book
    {
        $book = new Book($attributes);
        $book->saveQuietly();

        return $book;
    }
}

Mass update versus per-row save:

Mass updatePer-row save()
Statements11 SELECT + N UPDATE
Events and observersnot firedfired
Casts, mutatorsnot appliedapplied
updated_atnot touchedset
Dirty tracking (isDirty, wasChanged)no modelworks
Lock durationone statement, may lock many rows at onceshort per row
Race with another writerone atomic SET x = x * 0.9read-modify-write: lost update

The Laravel docs state: "When issuing a mass update via Eloquent, the saving, saved, updating, and updated model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update." The same holds for mass delete and for insert, upsert and insertOrIgnore. If an observer sends a cache-busting event, writes an audit row or updates a search index, a bulk path bypasses it: dispatch the work yourself, or write through the model in chunks (chunkById plus save) when the behaviour matters more than the speed. saveQuietly() and Model::withoutEvents(fn) go the other way: they run the model path but mute events.

sql
-- one atomic statement, no race
UPDATE books SET price_cents = price_cents * 9 / 10, updated_at = now() WHERE author_id = 7;
-- upsert, PostgreSQL
INSERT INTO books (sku, author_id, title, price_cents)
VALUES ('a-1', 7, 'Dune', 900), ('a-2', 7, 'Emma', 700)
ON CONFLICT (sku) DO UPDATE SET title = EXCLUDED.title, price_cents = EXCLUDED.price_cents;

Implicit transactions and the transaction boundary Must-know ​

In plain words: Every statement runs in some transaction. If you did not open one, the database opens and commits one per statement; a loop of 300 saves is 300 separate commits.

Common misunderstanding: "My service method is one unit of work, so it is one transaction." Without DB::transaction or db.BeginTx it is as many transactions as statements, and a crash halfway leaves half the work committed.

Definition: the transaction boundary is the pair of BEGIN and COMMIT around the statements that must succeed together. The ORM may add its own: GORM wraps each create, update or delete in a transaction by default. Its docs say it performs "write (create/update/delete) operations run inside a transaction to ensure data consistency" and that you can disable it with SkipDefaultTransaction: true for "about 30%+ performance improvement". Laravel does not: save() outside DB::transaction is an autocommit statement. Only a call whose documentation says so wraps itself, for example deleteOrFail, which the docs describe as rolling back on an exception.

text
     No explicit transaction                      With DB::transaction
1    INSERT book 1  -> autocommit, durable        BEGIN
2    INSERT book 2  -> autocommit, durable        INSERT book 1; INSERT book 2; INSERT book 3
3    process crashes                              process crashes -> ROLLBACK, nothing stored
4    INSERT book 3  -> never runs                 (or) COMMIT: all three durable
     -- 2 of 3 books exist, no error shown

Three consequences to design for. Atomicity of a batch needs the explicit boundary; the ACID basics are in ACID & Transactions. Transaction length: a transaction around a loop that also calls an HTTP API holds locks and a connection for the duration (see Connection Pooling); keep the boundary around the database work only. Side effects (email, queue) must run after commit: in Laravel use DB::afterCommit, a queued job with afterCommit, or ShouldDispatchAfterCommit on events; in Go run them after tx.Commit() returns. Nested DB::transaction calls use savepoints; attempts retries a deadlock or serialization failure, see Deadlocks.

sql
BEGIN;
INSERT INTO books (author_id, sku, title) VALUES (1, 'x-1', 'A'), (1, 'x-2', 'B');
UPDATE authors SET books_count = books_count + 2 WHERE id = 1;
COMMIT;
go
// Go: one boundary around related writes; GORM
err := db.Transaction(func(tx *gorm.DB) error {
	if err := tx.Create(&books).Error; err != nil {
		return err // rolls back
	}
	return tx.Model(&author).Update("books_count", gorm.Expr("books_count + ?", len(books))).Error
})
php
DB::transaction(function () use ($rows, $authorId) {
    Book::insert($rows);
    Author::whereKey($authorId)->increment('books_count', count($rows));
}, attempts: 3);

No identity map in Eloquent Important ​

In plain words: Ask Eloquent for the same row twice and you get two different objects. Change one and the other does not know.

Common misunderstanding: "find(1) returns the same object each time, like a session cache." That is a Data Mapper feature (Doctrine, Hibernate). Eloquent, GORM and Rails build a fresh instance per query.

Definition: an identity map keeps each loaded entity once per unit of work, keyed by primary key, so a second load returns the existing instance. Fowler: "Ensures that each object gets loaded only once by keeping every loaded object in a map."

text
     Eloquent                                    Doctrine EntityManager
1    $a = Book::find(1);   // SELECT             $a = $em->find(Book::class, 1);   // SELECT
2    $b = Book::find(1);   // SELECT again       $b = $em->find(Book::class, 1);   // from the map
3    $a->title = 'X'; $a->save();                $a->setTitle('X');
4    $b->title                                   $b->getTitle()  // 'X': same object
     -- 'old title': $b is stale                 $em->flush();   // one UPDATE

Real scenarios: two services in one request each load the user and edit different fields, and the second save() overwrites the first (with default dirty tracking only the changed attributes are written, so this is usually safe; a full-row save such as GORM's Save is not); a test compares two instances with === and fails; code that reloads a model inside a loop to "get fresh data" doubles queries. Fixes: pass the model object down rather than the id; call $book->refresh() when you want the database's current state; use fresh() for a new instance; or move to a Data Mapper ORM when the domain model is rich.

ORMIdentity mapUnit of WorkDirty tracking
Eloquentnono (explicit save)per model (isDirty)
GORMnonoSave writes all fields; Updates writes given fields
Doctrine ORMyes (EntityManager)yes (flush)automatic, by snapshot comparison
Hibernate / JPAyes (session)yes (flush)automatic
SQLAlchemy ORMyes (Session)yesautomatic
Rails ActiveRecordper-request query cache onlynoper model
Djangononosave() writes all fields unless update_fields
Entnonoexplicit builders

Caching pitfalls Important ​

In plain words: A cache in front of the ORM makes reads fast and makes it easy to serve a stale or wrong object.

Common misunderstanding: "Cache::remember on a model is free." It serialises a snapshot: later writes do not change it, cached objects hide lazy loads (the relation may be missing after unserialize), and a cache hit skips events and scopes you thought applied.

Definition: the places where an ORM-adjacent cache goes wrong: caching hydrated models instead of arrays, missing invalidation on bulk writes (which fire no events, so event-based invalidation never runs), cache stampede on a hot key, caching a per-user result under a global key, and the check-then-set race of a read-through cache. The query cache inside one request (Rails' per-request cache, Hibernate's second-level cache) is a different thing and is off by default in Eloquent.

PitfallWhy it happensFix
Cached model carries an unloaded relationLazy load after unserialize runs a query or throws under strictnessCache arrays or DTOs, not models
Bulk update leaves cache staleupdate() fires no updated event, so the observer that clears the cache does not runInvalidate in the same code path, or version the key
StampedeMany requests miss together and all queryCache::lock, remember with jitter, stale-while-revalidate
Write-then-read from a replicaThe cache fills from a stale replicaRead primary after write, see Replication
Cache written before commitReader sees data that is rolled backWrite the cache in DB::afterCommit
Cache inside the transactionLost update through the cacheDelete the key after commit, do not rewrite it; see Isolation Levels
php
// version the key so a bulk update invalidates without events
$version = Cache::get('books:version:'.$authorId, 1);
$titles = Cache::remember("books:{$authorId}:v{$version}", 300, fn () =>
    Book::where('author_id', $authorId)->pluck('title', 'id')->all());

DB::transaction(function () use ($authorId) {
    Book::where('author_id', $authorId)->update(['in_stock' => false]);
    DB::afterCommit(fn () => Cache::increment('books:version:'.$authorId));
});

Query builder vs raw SQL, and SQL injection through raw Must-know ​

In plain words: The ORM protects you only for the values it binds. Anything you glue into a string yourself is yours to protect.

Common misunderstanding: "I use an ORM, so I cannot have SQL injection." Eloquent's where('name', $x) binds $x; whereRaw("name = '$x'"), orderBy($request->sort), DB::unprepared($sql) and selectRaw with interpolated values do not. The Laravel docs say the query builder "uses PDO parameter binding to protect your application against SQL injection attacks", that "PDO does not support binding column names", and that "Laravel cannot guarantee that any query using raw expressions is protected against SQL injection vulnerabilities".

Definition: a value is safe when it travels as a bound parameter (?, $1, :name) and the SQL text is a constant. Identifiers (column and table names, ORDER BY direction, LIMIT in some drivers) cannot be bound and must come from a whitelist.

text
     Request: GET /books?sort=title;DROP TABLE books--
1    Book::orderBy($request->query('sort'))     -> ORDER BY "title;DROP TABLE books--" (quoted by Laravel; fails, safe)
2    Book::orderByRaw($request->query('sort'))  -> ORDER BY title;DROP TABLE books--     (injection)
3    DB::select("... WHERE id = $id")           -> id = 1 OR 1=1                          (injection)
4    DB::select('... WHERE id = ?', [$id])      -> id = $1 bound as text '1 OR 1=1'      (safe, returns nothing)
TechniqueSafe?Note
where('col', $value)yesBinding
whereRaw('lower(name) = ?', [$v])yesBinding in raw
whereRaw("lower(name) = '$v'")noConcatenation
orderBy($col) with user inputnoWhitelist the column
DB::unprepared($sql)noThe docs: "never allow user controlled values"
whereIntegerInRaw('id', $ids)yes if the values are cast to intInlines integers on purpose to save memory
GORM Where("name = ?", v)yesBinding
GORM Where("name = '" + v + "'")noConcatenation
database/sql $1 / ?yesServer-side or driver-side binding
sqlc generated functionsyesParameters are arguments

When raw SQL is the right tool: a report with window functions, a recursive CTE, FOR UPDATE SKIP LOCKED, COPY, a hand-tuned join. Use the query builder for dynamic filters (it composes), a model for single-entity behaviour, and raw SQL (or sqlc) for fixed analytic queries. The injection topic in depth, with prepared statements and roles, is in Database Security.

sql
-- the dynamic part: validated column, bound value
SELECT id, title FROM books WHERE title ILIKE $1 ORDER BY created_at DESC LIMIT 20;
go
var allowed = map[string]string{"title": "title", "created": "created_at"}

func list(ctx context.Context, db *sql.DB, term, sort string) (*sql.Rows, error) {
	col, ok := allowed[sort]
	if !ok {
		col = "created_at"
	}
	// col comes from the whitelist; term travels as a parameter.
	return db.QueryContext(ctx, "SELECT id, title FROM books WHERE title ILIKE $1 ORDER BY "+col+" DESC LIMIT 20", "%"+term+"%")
}
php
$column = in_array($request->query('sort'), ['title', 'created_at'], true) ? $request->query('sort') : 'created_at';
Book::where('title', 'ilike', '%'.$request->query('q').'%')->orderBy($column, 'desc')->limit(20)->get();

ORM-generated bad SQL: OR chains, huge IN, correlated subqueries Important ​

In plain words: The ORM writes the SQL you described, not the SQL the planner likes. Some perfectly natural PHP or Go produces statements that are slow or that break limits.

Common misunderstanding: "If the code is clean the SQL is fine." The shapes below are clean in code and expensive in SQL.

Definition: query shapes that ORMs produce easily and databases handle badly.

ShapeProduced byProblemFix
IN with thousands of idswhereIn('id', $ids) after a big pluckLong parse, parameter limit (65,535), a plan per distinct list lengthJoin on a temp table, = ANY($1) with one array, whereIntegerInRaw, chunk the ids
Long OR chainA loop adding orWherePostgreSQL can combine with BitmapOr; MySQL may fall to a scan; plan time growsIN, UNION ALL, a join on VALUES
OR across columnswhere('a', 1)->orWhere('b', 1)One index cannot serve bothTwo queries UNIONed, or an index per column and rely on bitmap-or
whereHasNested EXISTSCorrelated subquery per parent; slow on big tablesjoin with distinct, or whereIn on a subquery, check the plan
count(*) for paginationpaginate()Counts the whole filtered set on every pagesimplePaginate, cursorPaginate, cached or estimated count; see Pagination
OFFSET deep pagespaginate(), chunkReads and discards offset rowsKeyset
SELECT *defaultWide rows, no index-only scanSelect columns
LIKE '%x%'where('name', 'like', "%$x%")Cannot use a B-treepg_trgm GIN or full-text; see Full-Text Search
Function on an indexed columnwhereRaw('lower(email) = ?'), whereDate('created_at', $d)Index not usedExpression index, range predicate
N sortsorderBy on a computed aliasSort in memoryIndex matching the order
Casting mismatchBinding a string against an int columnImplicit cast defeats indexCast in the application
Prepared-statement plan flipPDO::ATTR_EMULATE_PREPARES off, generic planPostgreSQL may choose a generic plan after five executionsplan_cache_mode, see Query Planning
sql
-- IN with thousands of values
SELECT * FROM books WHERE id IN (1, 2, 3, /* ... 5,000 ... */ 5000);
-- one array parameter, one plan
SELECT * FROM books WHERE id = ANY($1::bigint[]);
-- the join form for huge lists
CREATE TEMP TABLE wanted (id bigint PRIMARY KEY);
-- COPY ids in, then:
SELECT b.* FROM books b JOIN wanted w ON w.id = b.id;

The generated SQL is readable. Eloquent: ->toRawSql(). The Laravel docs expose dumpRawSql and ddRawSql for the same purpose. Always read the statement before you accept the code, and run EXPLAIN (ANALYZE, BUFFERS) on it; see Mechanics and Query Planning.

Pagination Good to know ​

In plain words: paginate() is convenient, and each page costs a COUNT(*) plus an OFFSET scan.

Common misunderstanding: "Pagination is a UI feature." It is a query-shape choice with a cost curve; page 5,000 reads and throws away 100,000 rows.

Definition: Laravel offers paginate (page numbers, runs a count), simplePaginate (next/previous, no count) and cursorPaginate (keyset). GORM and sqlc do not paginate for you: you write LIMIT/OFFSET or a keyset predicate. The full cost model, row-value comparisons and opaque cursors are in Pagination: Offset vs Keyset; this page only warns that chunk is offset paging with a callback.

text
     paginate(25) on 40 million rows, page 4000
1    SELECT count(*) FROM books WHERE in_stock          -- full filtered scan
2    SELECT * FROM books WHERE in_stock ORDER BY id LIMIT 25 OFFSET 99975   -- reads 100,000 rows
     cursorPaginate(25): WHERE (id) > (?) ORDER BY id LIMIT 26  -- reads 26 rows

Soft deletes and indexes Important ​

In plain words: A soft delete marks a row as deleted instead of removing it. The row still occupies the table, still sits in every index, and still blocks unique values.

Common misunderstanding: "Soft delete is a safe DELETE." It changes every query (a hidden WHERE deleted_at IS NULL), keeps foreign keys alive, breaks unique constraints, and fails to meet erasure requirements.

Definition: Eloquent SoftDeletes sets deleted_at and adds a global scope; GORM does the same for models with a gorm.DeletedAt field ("If your model includes a gorm.DeletedAt field (which is included in gorm.Model), it will get soft delete ability automatically!"), and soft-deleted records are ignored when querying.

IssueWhyFix
Unique collisionemail unique index includes deleted rowsPostgreSQL partial unique index WHERE deleted_at IS NULL; MySQL: unique on (email, deleted_at) or a generated column
Slow queriesThe hidden predicate is not in your indexInclude deleted_at IS NULL in a partial index on hot paths
Table bloatDeleted rows never leavePurge job with chunkById + forceDelete; archive; partition by date
Foreign keysA child references a soft-deleted parentCascade soft delete in the model, or hard delete children
Raw queries and JOINsGlobal scope applies only to model queriesAdd the predicate to every raw query and to joins
CountswithCount counts deleted children unless scopedwithCount(['books' => fn ($q) => ...]); the relation's scope applies
unique validationRule sees deleted rowsRule::unique(...)->withoutTrashed()
PrivacyData is retainedHard delete or anonymise on request
sql
-- PostgreSQL: free the email when a user is soft deleted
CREATE UNIQUE INDEX users_email_active ON users (email) WHERE deleted_at IS NULL;
-- keep hot queries on the live subset small
CREATE INDEX books_author_live ON books (author_id) WHERE deleted_at IS NULL;
go
type Book struct {
	ID        uint
	Title     string
	DeletedAt gorm.DeletedAt `gorm:"index"` // soft delete, indexed
}
// db.Delete(&book) sets deleted_at; db.Unscoped().Delete(&book) removes the row.

Polymorphic relations and foreign-key loss Important ​

In plain words: One column (commentable_id) holds an id that may belong to different tables, and another (commentable_type) says which. The database cannot check that the id exists.

Common misunderstanding: "A polymorphic relation is a normal foreign key with a type." A foreign key points at one table; this one points at several, so no constraint is possible and orphans appear.

Definition: Eloquent morphTo, morphMany and morphs() columns; Rails polymorphic: true; Doctrine mapped by inheritance instead.

text
     comments(commentable_type, commentable_id)
1    ('book', 7)     -> books.id = 7
2    ('author', 7)   -> authors.id = 7
3    DELETE FROM books WHERE id = 7;      -- no FK: comment ('book', 7) now points at nothing
4    $comment->commentable                -- null; or N+1 across two tables when listed
ProblemEffectFix
No foreign keyOrphan rows after deleteDelete in model events or a job; a periodic orphan query; or avoid polymorphism
Class name in the type columnRenaming a class breaks dataRelation::enforceMorphMap(['book' => Book::class])
Eager loading across typesOne query per typemorphWith for nested relations; accept one query per type
Index(commentable_type, commentable_id) is neededmorphs() creates the composite index
Query for all comments of authors and booksHard in SQLSeparate relations, or a supertype table

Alternatives that keep integrity: one table per parent (book_comments, author_comments), a nullable column per parent with a CHECK (num_nonnulls(book_id, author_id) = 1), or a supertype table commentables that both parents reference. See Schema Design for the trade-offs.

sql
CREATE TABLE comments (
  id bigserial PRIMARY KEY,
  book_id bigint REFERENCES books(id) ON DELETE CASCADE,
  author_id bigint REFERENCES authors(id) ON DELETE CASCADE,
  body text NOT NULL,
  CHECK (num_nonnulls(book_id, author_id) = 1)
);

Timestamps and time zones Important ​

In plain words: created_at is whatever the application clock said, rendered in whatever zone the application and the database agree on, which may not be the same.

Common misunderstanding: "timestamp stores a moment." PostgreSQL timestamp stores a wall-clock reading without a zone; timestamptz stores a moment (UTC internally). MySQL DATETIME has no zone; TIMESTAMP converts to UTC and tops out in 2038.

Definition: Eloquent sets created_at/updated_at with now() in the application time zone (config('app.timezone'), UTC by default) on save(), touch(), create() and upsert (updates only); bulk insert and mass update do not touch them. GORM sets CreatedAt/UpdatedAt through autoCreateTime/autoUpdateTime using NowFunc.

PitfallExampleFix
Local time storedApp zone Asia/Tehran, a second service in UTC reads the same columnStore UTC, convert at the edge
timestamp without time zonePostgreSQL timestamp loses the offsettimestamptz (Laravel timestampTz)
Bulk write leaves updated_atupdate() or insert() skips timestampsSet them in the statement ('updated_at' => now())
Clock skewTwo app servers differ by secondsUse the database's now() for ordering, or a sequence
now() inside a transactionPostgreSQL now() is the transaction start timeclock_timestamp() if you need wall time
Daylight savingAdd 24 hours vs "same wall time tomorrow"Do date math in UTC
whereDate('created_at', $d)Function on the column kills the indexwhereBetween('created_at', [$start, $end])
Casts'immutable_datetime' vs datetimePrefer immutable casts, avoid in-place ->addDay() mutation
sql
SHOW timezone;                                  -- PostgreSQL session zone
SELECT now(), clock_timestamp(), current_setting('TimeZone');
ALTER TABLE books ALTER COLUMN published_at TYPE timestamptz USING published_at AT TIME ZONE 'UTC';

Optimistic locking in ORMs Important ​

In plain words: Add a version number to the row; an update succeeds only if the version is still the one you read.

Common misunderstanding: "The ORM prevents concurrent overwrites." Eloquent and GORM do not unless you add a version column yourself; save() writes the attributes you changed and the last writer wins. The mechanics, retry loops and when to prefer FOR UPDATE are in Optimistic vs Pessimistic Locking.

ORMBuilt-in version checkHow
Hibernate / JPAyes@Version; OptimisticLockException
Doctrine ORMyes#[Version] or LockMode::OPTIMISTIC; OptimisticLockException
Railsyeslock_version column; StaleObjectError
Djangono (third-party)F() expressions, select_for_update
Eloquentnowhere('version', $v)->update([... 'version' => $v + 1]) and check affected rows
GORMplugingorm.io/plugin/optimisticlock Version field; or manual Where("version = ?") and RowsAffected
EntnoHand-written predicate, UpdateOne(...).Where(...)
sql
UPDATE books SET title = $1, version = version + 1 WHERE id = $2 AND version = $3;
-- rows affected = 0  ->  someone else changed it: reload and retry or tell the user
php
$updated = Book::whereKey($id)->where('version', $version)
    ->update(['title' => $title, 'version' => $version + 1]);
if ($updated === 0) { throw new ConflictHttpException('Book was changed by someone else'); }

Migrations generated by ORMs Must-know ​

In plain words: Tools that compare your models with the database and write the migration for you do not know your table is 800 GB.

Common misunderstanding: "An auto-generated migration is safe because it is mechanical." It is mechanical, not production-aware: it renames by drop-and-add, adds NOT NULL with defaults that rewrite the table on older engines, creates indexes without CONCURRENTLY, and takes ACCESS EXCLUSIVE locks.

Definition: schema diff tools (Doctrine migrations:diff, Django makemigrations, Alembic --autogenerate, Atlas, GORM AutoMigrate, Ent's Schema.Create, Rails schema dumps) compare desired and actual schemas and emit DDL.

DangerWhat the diff emitsProduction-safe version
Rename columnDROP COLUMN + ADD COLUMN (data lost)RENAME COLUMN, or expand/contract with dual writes
New NOT NULL columnADD COLUMN ... NOT NULL DEFAULTAdd nullable, backfill in batches, then SET NOT NULL via a validated CHECK
New indexCREATE INDEXCREATE INDEX CONCURRENTLY (PostgreSQL), online DDL (MySQL)
New foreign keyADD FOREIGN KEYNOT VALID then VALIDATE CONSTRAINT
Change column typeALTER COLUMN TYPENew column, backfill, switch, drop
AutoMigrate at startup (GORM)Runs DDL on every deploy, from every podRun migrations as a separate job; never from the web process
Down migrationsNot testedForward-only fixes
Foreign key without index (PostgreSQL)Missing index on the referencing columnAdd it; deletes on the parent scan the child

The Laravel habit: php artisan migrate --pretend prints the SQL; read it. GORM AutoMigrate never drops unused columns, which hides drift. Details of expand/contract, lock levels and backfills are in Zero-Downtime Schema Migrations.

Per-ORM behaviour ​

Active Record vs Data Mapper, and the repository debate Important ​

In plain words: In Active Record the model object knows how to save itself. In Data Mapper the object is plain and another object does the saving.

Common misunderstanding: "Data Mapper is the cleaner, so it is the better choice." It costs more code and more concepts (unit of work, identity map, flush ordering, detached entities). For CRUD-heavy applications Active Record is faster to build; Data Mapper pays off when the domain model is rich and must not know the database.

Definition: Fowler's wording is in the vocabulary table. Active Record: Eloquent, Rails ActiveRecord, Django ORM. Data Mapper: Doctrine ORM, Hibernate, SQLAlchemy ORM, Entity Framework, Ent (generated builders, plain structs). Neither is the same as a query builder, which only builds SQL.

Active Record (Eloquent, Rails, Django)Data Mapper (Doctrine, Hibernate, Ent, sqlc)Book modelfields + rules + save() + find()one class: data, behaviour, persistencebooks tableone row = one objectSQL built by the model itselfPro: little code, easy to learn. Con: domain object knows SQL;tests need a database; no identity map.Book entityplain object, no SQLBookMapperRepository / EntityManagermapper reads and writes entityUnit of WorkIdentity Mapbooks table: mapper emits SQL on flush()Pro: domain stays pure, one object per row per session.Con: more code, the mapper has its own rules to learn.
QuestionActive RecordData Mapper
Where does persistence liveOn the modelIn a mapper / entity manager
Domain object knows SQLYes (inherits Model)No
Identity map, unit of workNoYes
Testing the domain without a databaseHardEasy
BoilerplateLowHigher
SurpriseHidden queries on property accessHidden queries on flush() and lazy proxies
Typical pitfallN+1, bulk bypasses eventsFlush order, stale entities after clear(), proxy initialisation
FitsCRUD apps, admin tools, startupsRich domains, long-lived systems, DDD

The repository pattern debate is the same question one level up. Fowler's definition says a repository "mediates between the domain and data mapping layers using a collection-like interface". The case for it: a single place for query code, a seam for tests, a stable interface when the ORM changes. The case against, common in the Laravel community: with Eloquent, a repository that wraps Model::find adds a layer with no new abstraction, leaks Eloquent types through its return values, and cannot express with() choices without growing a method per use case. A workable middle: a repository (or query object) per use case that returns plain data and declares its eager loading inside, so a view cannot trigger N+1.

What each ORM and library really does ​

ProductModelRelation loadingN+1 guardBulkNotes
Eloquent (Laravel 13)Active RecordLazy by default; with, load, withCountpreventLazyLoading, shouldBeStrict, automaticallyEagerLoadRelationshipsinsert, upsert, insertOrIgnore, mass updateNo identity map; chunk APIs
GORMActive-Record-style over structsNo lazy loading; Preload, Joinsnone: a query in a loop is the bugCreate(&slice), CreateInBatches, Clauses(OnConflict), FindInBatchesDefault transaction per write; hooks; soft delete via DeletedAt
database/sql + pgxNoneYou write every querynonepgx.Batch, CopyFrom, unnestFull control; rows.Close() discipline
sqlxThin: struct scanning and named parametersYou write every querynoneNamedExec with a slice, sqlx.InSelect, Get, StructScan; no relations
sqlcCode generation from SQLYou write the join or the INnone; N+1 only if you call a generated function in a loop:copyfrom, :batchexec (pgx), sqlc.slice (MySQL, SQLite)Compile-time type checking of SQL against the schema
EntData-Mapper-style, generated graph APIWithPosts()-style eager loading, separate queriesnone, but loading is explicitCreateBulk, OnConflictSchema as Go code, code generation
BunQuery builder + modelsRelation("Author") joins for has-one and uses separate queries for has-manynoneNewInsert().Model(&slice), On("CONFLICT"), bun.Inbundebug query hook prints SQL
Doctrine ORM (PHP)Data MapperLazy proxies, EXTRA_LAZY, JOIN FETCH in DQLnone built in; $em->getUnitOfWork() inspectableDQL UPDATE/DELETE, batch with flush()+clear()Identity map, unit of work, #[Version]
Hibernate / JPAData MapperLazy by default for collections; @EntityGraph, JOIN FETCH, @BatchSizeLazyInitializationException after closeJDBC batching (hibernate.jdbc.batch_size)Second-level cache
SQLAlchemyData Mapper + Coreselectinload, joinedload, lazy="raise"lazy="raise"insert().values([...]), bulk_insert_mappingsIdentity map in Session
Rails ActiveRecordActive Recordincludes, preload, eager_loadstrict_loading, bullet geminsert_all, upsert_all, update_alllock_version optimistic locking
Django ORMActive Recordselect_related, prefetch_relatednone built inbulk_create, bulk_update, update()QuerySet is lazy until iterated

GORM, sqlx, pgx, sqlc, Ent and Bun in Go, in practice:

go
// sqlc: write SQL, get typed Go. queries.sql
// -- name: BooksByAuthors :many
// SELECT id, author_id, title FROM books WHERE author_id = ANY($1::bigint[]);
// -- name: InsertBooks :copyfrom
// INSERT INTO books (sku, author_id, title) VALUES ($1, $2, $3);
//
// generated (shape):
//   func (q *Queries) BooksByAuthors(ctx context.Context, ids []int64) ([]Book, error)
go
// sqlx: scan into structs, expand IN lists
query, args, _ := sqlx.In("SELECT id, title FROM books WHERE author_id IN (?)", ids)
query = db.Rebind(query)
var books []Book
err := db.SelectContext(ctx, &books, query, args...)
go
// Ent: explicit eager loading, one extra query per edge
authors, err := client.Author.Query().WithBooks().All(ctx)
// Bun: has-one by JOIN
err = db.NewSelect().Model(&books).Relation("Author").Scan(ctx)
php
// Doctrine: DQL with JOIN FETCH avoids the proxy N+1
$authors = $em->createQuery('SELECT a, b FROM App\Entity\Author a JOIN a.books b')->getResult();

The sqlc docs describe the tool in one line: "sqlc generates fully type-safe idiomatic Go code from SQL." The GORM docs describe Preload and Joins as above. Features I describe for Ent, Bun, Doctrine, Hibernate, SQLAlchemy, Rails and Django come from their documentation (pages saved for Ent, Bun and Doctrine; the rest from memory of the public docs, so check the exact method names in the version you run).

Mechanics ​

Reading what the ORM sends Must-know ​

You cannot fix what you cannot see. Every ORM has a way to print the SQL; use it before and after every performance change.

ToolWhat it showsHow
Eloquent toSql() / toRawSql()The statement, with ? or with bindings filled inBook::where(...)->toRawSql()
Eloquent dumpRawSql() / ddRawSql()Same, printed in the requestChain on the builder
DB::listenEvery statement after it runs: $query->sql, $query->bindings, $query->time (ms), $query->toRawSql()In a service provider
DB::enableQueryLog() / DB::getQueryLog()An in-memory listTests and tinker
DB::pretend(fn)The statements a closure would run, without running themphp artisan migrate --pretend
Laravel Telescope, Debugbar, PulsePer-request query list, duplicates, slow queriesInstall in non-production
GORM db.Debug()Logs each statement with duration and rowsdb.Debug().Find(&x)
GORM db.ToSQL(fn) and DryRun: trueSQL without executingtx.Statement.SQL.String()
GORM loggerlogger.Default.LogMode(logger.Info), SlowThresholdgorm.Config{Logger: ...}
pgx tracelog / QueryTracerStatements with arguments and timingpgx.ConnConfig.Tracer
database/sql db.Stats()Pool countersOpenConnections, WaitCount; see Connection Pooling
PostgreSQL log_min_duration_statementSlow statements in the server logALTER SYSTEM SET log_min_duration_statement = '200ms'
pg_stat_statementsCalls, mean time and rows per normalised statementA statement with calls in the millions and tiny mean_exec_time is an N+1
auto_explainPlans of slow statements in the logauto_explain.log_min_duration
MySQL slow query log, performance_schemaSamelong_query_time
EXPLAIN (ANALYZE, BUFFERS)The plan; see Query PlanningPaste the toRawSql() output
php
// AppServiceProvider::boot, non-production: flag repeated statements
$seen = [];
DB::listen(function (QueryExecuted $q) use (&$seen) {
    $seen[$q->sql] = ($seen[$q->sql] ?? 0) + 1;
    if ($seen[$q->sql] === 10) {
        logger()->warning('possible N+1', ['sql' => $q->sql, 'sample' => $q->toRawSql()]);
    }
});

The telltale of an N+1 in pg_stat_statements is one normalised statement (... WHERE author_id = $1) with a huge calls count and a tiny mean_exec_time, next to a parent statement with far fewer calls.

Knobs Important ​

KnobProductEffect
Model::preventLazyLoading($bool)LaravelThrow on lazy load
Model::shouldBeStrict($bool)LaravelThree checks at once
Model::preventSilentlyDiscardingAttributes()LaravelThrow instead of dropping unfillable attributes
Model::preventAccessingMissingAttributes()LaravelThrow on unselected attributes
Model::automaticallyEagerLoadRelationships()LaravelBatch lazy loads of siblings
Model::handleLazyLoadingViolationUsing(fn)LaravelLog instead of throw
protected $with, $withCountLaravelAlways eager load
$fillable, $guarded, Model::unguard()LaravelMass-assignment policy
PDO::ATTR_EMULATE_PREPARESPHP PDOClient-side vs server-side prepare
SkipDefaultTransactionGORMRemove the per-write transaction
PrepareStmtGORMCache prepared statements per connection
DryRun, Logger, NowFuncGORMDebugging and clock control
CreateBatchSizeGORMDefault batch for Create(&slice)
SetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetimedatabase/sqlPool limits; a loop of N queries holds one connection
jdbc.batch_size, fetch_sizeHibernateStatement batching, streaming
plan_cache_mode, max_prepared_transactions, statement_timeout, idle_in_transaction_session_timeoutPostgreSQLPlan reuse, timeouts for runaway ORM loops
max_allowed_packet, max_prepared_stmt_countMySQLLimits for giant INSERTs

Error messages you will meet Must-know ​

MessageProductMeaningFix
Attempted to lazy load [books] on model [App\Models\Author] but lazy loading is disabled. (LazyLoadingViolationException)LaravelpreventLazyLoading caught a lazy loadAdd with
The attribute [x] either does not exist or was not retrieved for model [...] (MissingAttributeException)LaravelYou narrowed select and read a missing columnSelect it
Add [x] to fillable property to allow mass assignment on [...] (MassAssignmentException)Laravelcreate($request->all()) with an unfillable key$fillable
Allowed memory size of ... bytes exhaustedPHPall() or eager loading too muchchunkById, lazy, select columns
SQLSTATE 23505 duplicate key value violates unique constraint / MySQL 1062PostgreSQL / MySQLUnique violation; soft-deleted row countsPartial unique index; upsert
SQLSTATE 40001 / 40P01 / MySQL 1213PostgreSQL / MySQLSerialization failure or deadlockRetry the whole transaction; see Deadlocks
number of parameters must be between 0 and 65535 (pgx: extended protocol limited to 65535 parameters)PostgreSQL / pgxMulti-row insert too bigBatch, unnest, COPY
MySQL 1390 Prepared statement contains too many placeholdersMySQLSameBatch
WHERE conditions required (gorm.ErrMissingWhereClause)GORMDelete/Update with no conditionAdd a condition
record not found (gorm.ErrRecordNotFound)GORMFirst, Take, Last found nothingCheck with errors.Is
sql: Rows are closed, pool exhaustion context deadline exceededdatabase/sqlForgot rows.Close() or a long loop holds connectionsdefer rows.Close(); see Connection Pooling
LazyInitializationExceptionHibernateTouched a lazy proxy after the session closedJOIN FETCH, DTOs

Solving the classic problems ​

N+1 in a list endpoint ​

SolutionHowAdvantageCost / limit
with / Preload / selectinloadSecond query with INSimple, works for has-manyResult set in memory; big IN
withCount / withSumSubquery per aggregateNo child rows loadedOne subquery per aggregate
JOINOne statementOne round tripDuplicates parent columns; breaks LIMIT on parent
DTO query (raw / sqlc)You write the exact shapeMinimal dataMore code
preventLazyLoading in CIFail on lazy loadCatches regressionsOnly paths that tests execute
DataLoader (GraphQL)Batch per request tickFixes resolver N+1Needs a batching layer
Denormalised counter columnbooks_count maintained on writeReads become freeWrite complexity, drift

Code: N+1 section and eager loading.

Importing a file of 1,000,000 rows ​

SolutionHowAdvantageCost / limit
Per-row save()LoopEvents and validationHours; one commit per row
Batched insert / upsert in one transaction500-1,000 rows per statement50 to 500 times fasterNo events; validation is yours
Staging table + INSERT ... SELECTLoad raw, transform in SQLSet-based, restartableExtra table
COPY (pgx CopyFrom)Wire protocol bulkFastestNo ON CONFLICT; whole load fails on one bad row
Queue per chunkOne job per 1,000 rowsParallel, retryableIdempotency required; see Idempotent Consumer
php
public function import(string $path): void
{
    $batch = [];
    foreach ($this->rows($path) as $row) {           // generator: constant memory
        $batch[] = $row + ['updated_at' => now(), 'created_at' => now()];
        if (count($batch) === 1000) {
            Book::upsert($batch, uniqueBy: ['sku'], update: ['title', 'price_cents', 'updated_at']);
            $batch = [];
        }
    }
    if ($batch) { Book::upsert($batch, ['sku'], ['title', 'price_cents', 'updated_at']); }
}

A sweep that updates what it reads ​

Use chunkById or lazyById in Laravel, FindInBatches or a hand-written keyset loop in Go (the chunk package), or one set-based UPDATE ... WHERE when no per-row logic is needed. For a table with hundreds of millions of rows, bound each batch and commit between them to avoid long locks and bloat; see Working with Billion-Row Tables.

sql
-- batch of 5,000 per statement, repeat until 0 rows
UPDATE books SET in_stock = false
WHERE id IN (SELECT id FROM books WHERE in_stock AND author_id = 7 ORDER BY id LIMIT 5000 FOR UPDATE SKIP LOCKED);

Reporting queries ​

A report that joins five tables and aggregates a million rows is a SQL problem. Write it as SQL (query builder selectRaw/groupBy, DB::select, or sqlc), read the plan, and return plain rows. Run it on a replica or in a materialised view when it is heavy; see OLTP vs OLAP and Replication.

sql
SELECT a.id, a.name, count(b.id) AS books, sum(b.price_cents) AS value
FROM authors a LEFT JOIN books b ON b.author_id = a.id AND b.deleted_at IS NULL
GROUP BY a.id, a.name ORDER BY value DESC NULLS LAST LIMIT 50;

Testing: real database or mocks ​

In plain words: A mocked ORM proves your code calls the mock. Only a real database proves the SQL.

Common misunderstanding: "Mocking the repository makes tests fast and equally good." Mocks cannot catch N+1, wrong joins, unique violations, NULL behaviour, collation or migrations.

ApproachCatchesMissesSpeed
Mocks / fakes of the ORMControl flowEverything about SQLFastest
SQLite in memory (Laravel default for tests)Basic logicPostgreSQL-specific features: ON CONFLICT, jsonb, partial indexes, timestamptz, lockingFast
Real PostgreSQL / MySQL in a container (Testcontainers, Docker Compose)SQL, constraints, migrations, plansProduction-scale dataSeconds to start
Transaction rollback per test (RefreshDatabase, DatabaseTransactions; Go: BEGIN/ROLLBACK)Isolation between testsCode that commits or uses multiple connectionsFast
Query-count assertionsN+1 regressionsSlow single queriesFast
EXPLAIN in CI on key queriesMissing index regressionsData-dependent plansMedium

Rules that work: run migrations on the same engine you deploy; keep a small realistic seed; assert query counts for list endpoints; turn on shouldBeStrict in the test bootstrap; prefer transaction-per-test cleanup; and test concurrency features on a real server (see the isolation lab).

php
public function test_author_index_uses_two_queries(): void
{
    Author::factory()->count(20)->hasBooks(3)->create();
    DB::enableQueryLog();
    $this->getJson('/authors')->assertOk();
    $this->assertLessThanOrEqual(3, count(DB::getQueryLog()));
}
go
func countingDB(t *testing.T, db *gorm.DB) *atomic.Int64 {
	var n atomic.Int64
	_ = db.Callback().Query().After("gorm:query").Register("test:count", func(*gorm.DB) { n.Add(1) })
	return &n
}

Choosing a tool ​

OperationRecommended toolExtra techniqueReason
Single-entity create/update with rulesModel (save, GORM Save)Observers, validation, transactionBehaviour lives on the model
List with relationswith / PreloadSelect columns, preventLazyLoadingFixed query count
Counts and sums of childrenwithCount, withSumCached counter if hotNo child rows loaded
Filter parents by childrenwhereHas or JOINCheck the planEXISTS vs join choice depends on data
Dynamic search filtersQuery builderBindings, whitelisted columnsComposable and safe
Reports and analyticsRaw SQL / sqlcEXPLAIN, replica, materialised viewThe planner needs the whole shape
Walk a big table with updateschunkById, lazyById, keysetCommit per batchNo skipped rows
Read-only pass over a big tablelazy or cursorselect columnsConstant memory
Bulk importBatched upsert in one transaction, or COPYStaging tableStatement count
Bulk change needing eventschunkById + saveQueue the heavy partEvents are the reason
Money, stock, balancesAtomic UPDATE, FOR UPDATE, version columnIdempotency keysNot read-modify-write; see Isolation Levels
Hot path in Gopgx or sqlcPrepared statementsExact SQL, typed rows
Rich domain in PHP or JavaData Mapper (Doctrine, Hibernate)Repository per aggregateIdentity map and unit of work

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

An Eloquent monolith with strict mode on in CI is the simplest correct setup. Every list endpoint declares its with; a feature test asserts the query count; chunkById does the batch jobs; DB::transaction wraps each use case. Example: a store with orders, order_items, customers. The order list loads Order::with('customer:id,name')->withCount('items')->cursorPaginate(25): two queries per page, constant memory, no lazy loading.

Modular monolith and multiple databases ​

When modules own their tables, a relation across modules is a boundary violation. Eloquent relations that cross modules (an Order with belongsTo(Customer::class) from another module) couple schemas and make with impossible if the tables live in different databases (Eloquent can use per-model connections, but no cross-database JOIN exists). Replace the relation with an id and a read-model call: the orders module asks the customers module for customersByIds($ids) in one batch, which is eager loading by hand. Each module gets its own migrations, and each uses its own DB::transaction (a single-connection boundary).

Microservices: no ORM across the wire ​

A relation cannot cross a service boundary: the ORM cannot join orders (service A) with customers (service B). The N+1 moves from SQL to HTTP: a loop that calls GET /customers/{id} per order is the same fan, with latencies in the tens of milliseconds and failure modes. Fix with batch endpoints (GET /customers?ids=1,2,3), a local read model fed by events (see Outbox), or a gateway aggregation. Each service keeps its own ORM and its own DB::transaction; cross-service atomicity needs a saga (see Saga) because no ORM transaction spans services. Bulk operations inside a service must still publish events that the ORM bypassed: a mass update() fires no model event, so a downstream cache or search index never hears of it; write an outbox row in the same transaction as the bulk update.

text
     Order service (Eloquent)                          Event consumers
1    BEGIN
2    UPDATE books SET in_stock = false WHERE author_id = 7   -- mass update: no model event
3    INSERT INTO outbox (type, payload) VALUES ('author.out_of_stock', '{"author":7}')
4    COMMIT
5    relay publishes 'author.out_of_stock'  -------------->  search index and cache update

Distributed data: replicas, caches and distributed SQL ​

Read replicas (see Replication & Failover) turn an ORM's hidden read after write into a bug: save() then redirect then find() may read a lagging replica. Laravel's sticky connection option keeps reads on the primary after a write in the same request; in Go, route by explicit transaction or pool. A cache around the ORM (see caching pitfalls) and bulk writes that skip events leave stale entries. On distributed SQL (CockroachDB, Spanner, YugabyteDB) an N+1 costs cross-region round trips and a transaction may retry with 40001: the ORM must retry the whole unit of work (see Distributed SQL). Default isolation differs by product (CockroachDB Serializable, PostgreSQL and Oracle Read Committed, InnoDB Repeatable Read), which changes what a read-modify-write through an ORM can lose; see Isolation Levels.

Scaling path: 1×, 10×, 100× ​

LoadORM-level concernWhat to do
1× (a few hundred rows per list)N+1 is invisibleTurn on strict mode and query-count tests now, because this is when the habit is formed
10×N+1 shows in p95; paginate() counts get slow; chunk jobs take minuteswith everywhere, cursorPaginate, chunkById, indexes on foreign keys, pg_stat_statements in review
100×Hydration cost, connection pool pressure, bulk write contention, replica lagDTO or sqlc for hot reads, batched writes with outbox, read replicas with read-your-writes routing, partition big tables, move reports to OLAP; see Storage & Data Scaling

Lab ​

Two terminals are not needed here; one shell and one psql. Expected output is in comments.

Setup.

bash
docker run -d --name pg -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17
docker exec -it pg psql -U postgres -c 'CREATE DATABASE lab'
export DATABASE_URL=postgres://postgres:pg@localhost:5432/lab
sql
-- psql -U postgres -d lab
CREATE TABLE authors (id bigserial PRIMARY KEY, name text NOT NULL);
CREATE TABLE books (
  id bigserial PRIMARY KEY,
  author_id bigint NOT NULL REFERENCES authors(id),
  sku text UNIQUE,
  title text NOT NULL,
  price_cents int NOT NULL DEFAULT 0,
  in_stock boolean NOT NULL DEFAULT true
);
CREATE INDEX books_author_id ON books (author_id);
INSERT INTO authors (name) SELECT 'author ' || g FROM generate_series(1, 200) g;
INSERT INTO books (author_id, sku, title)
SELECT (g % 200) + 1, 'sku-' || g, 'book ' || g FROM generate_series(1, 5000) g;

Experiment 1: produce an N+1 with GORM, count it, fix it.

text
1    cd docs/snippets/database/orm-pitfalls/go && go run ./gorm
2    n+1          201 queries
3    preload      2 queries
4    joins        1 queries
5    SELECT "books"."id", ... "Author"."name" AS "Author__name" FROM "books" LEFT JOIN "authors" "Author" ON ...
     -- the counts are from the 200 authors above; with 20 authors the first line says 21

Experiment 2: produce an N+1 with Eloquent, count it, fix it. Add the models and migration from the snippets (php artisan migrate), seed 200 authors and 5,000 books, then in php artisan tinker:

The lab files, in order: models, migration, and the Lab helper class.

php
<?php

// Models and migration used by the lab: authors have many books, books have
// many comments through a polymorphic relation, and books are soft deleted.

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;

final class Author extends Model
{
    use HasFactory;

    protected $fillable = ['name'];

    public function books(): HasMany
    {
        return $this->hasMany(Book::class);
    }
}

final class Book extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $fillable = ['author_id', 'sku', 'title', 'price_cents', 'in_stock'];

    protected $casts = ['in_stock' => 'boolean', 'published_at' => 'immutable_datetime'];

    public function author(): BelongsTo
    {
        return $this->belongsTo(Author::class);
    }

    public function comments(): MorphMany
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

final class Comment extends Model
{
    protected $fillable = ['commentable_type', 'commentable_id', 'body'];

    // commentable_id can point at books or authors, so the database cannot
    // declare a foreign key for it. Register Relation::enforceMorphMap(
    // ['book' => Book::class, 'author' => Author::class]) in a service provider
    // so commentable_type stores short stable names instead of class names.
}
php
<?php

// Migration for the lab. Read the SQL an ORM migration will run before you
// ship it: php artisan migrate --pretend

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('authors', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });

        Schema::create('books', function (Blueprint $table) {
            $table->id();
            // foreignId()->constrained() creates the FK and, on MySQL, an index.
            // PostgreSQL does NOT index the referencing column: add it yourself.
            $table->foreignId('author_id')->constrained();
            $table->string('sku')->unique();
            $table->string('title');
            $table->unsignedInteger('price_cents')->default(0);
            $table->boolean('in_stock')->default(true);
            $table->timestampTz('published_at')->nullable();
            $table->timestamps();
            $table->softDeletes();
            $table->index('author_id');
            // Serves the chunkById sweep: WHERE in_stock = true AND id > ? ORDER BY id.
            // The unique sku index still counts soft-deleted rows; see the page.
            $table->index(['in_stock', 'id']);
        });

        Schema::create('comments', function (Blueprint $table) {
            $table->id();
            $table->morphs('commentable'); // commentable_type + commentable_id + index, no FK
            $table->text('body');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('comments');
        Schema::dropIfExists('books');
        Schema::dropIfExists('authors');
    }
};
php
<?php

// Lab helpers: count the queries a piece of code sends, produce an N+1, fix it,
// and compare chunk() with chunkById(). Run it from `php artisan tinker` or a
// console command against the lab database.

namespace App\Lab;

use App\Models\Author;
use App\Models\Book;
use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;

final class Lab
{
    /**
     * Runs $work and returns how many SQL statements it sent.
     * DB::listen fires for every statement on the default connection.
     */
    public static function countQueries(Closure $work): int
    {
        $count = 0;
        DB::listen(function (QueryExecuted $query) use (&$count) {
            $count++;
            // $query->toRawSql() is the statement with its bindings filled in.
            // $query->time is the execution time in milliseconds.
        });

        $work();

        return $count;
    }

    public static function nPlusOne(): int
    {
        return self::countQueries(function () {
            foreach (Author::all() as $author) {
                $author->books->count(); // lazy load: one query per author
            }
        });
    }

    public static function fixed(): int
    {
        return self::countQueries(function () {
            // with() = 1 query for authors + 1 query for all their books.
            foreach (Author::with('books:id,author_id,title')->get() as $author) {
                $author->books->count();
            }
        });
    }

    public static function countedInSql(): int
    {
        return self::countQueries(function () {
            // withCount() = 1 query. withSum('books', 'price_cents') works the same way.
            foreach (Author::withCount('books')->get() as $author) {
                $author->books_count;
            }
        });
    }

    /** Throws instead of lazy loading, so a missed with() fails in tests. */
    public static function strict(): void
    {
        Model::preventLazyLoading();
        Model::handleLazyLoadingViolationUsing(function (Model $model, string $relation) {
            logger()->warning('lazy loading', ['model' => $model::class, 'relation' => $relation]);
        });
    }

    /** The SQL Eloquent will send, without running it. */
    public static function readTheSql(): string
    {
        return Author::query()
            ->withCount('books')
            ->whereHas('books', fn ($q) => $q->where('in_stock', true))
            ->toRawSql();
    }

    /**
     * Visits every in-stock book and flips it out of stock. Returns how many
     * rows the loop saw. With chunk() the answer is about half the table.
     */
    public static function chunkVisited(): int
    {
        $seen = 0;
        Book::where('in_stock', true)->chunk(100, function ($books) use (&$seen) {
            foreach ($books as $book) {
                $book->update(['in_stock' => false]);
                $seen++;
            }
        });

        return $seen;
    }

    /** Same work with chunkById(): pages by id, so every row is visited once. */
    public static function chunkByIdVisited(): int
    {
        $seen = 0;
        Book::where('in_stock', true)->chunkById(100, function ($books) use (&$seen) {
            foreach ($books as $book) {
                $book->update(['in_stock' => false]);
                $seen++;
            }
        });

        return $seen;
    }
}
text
1    >>> App\Lab\Lab::nPlusOne()
2    => 201
3    >>> App\Lab\Lab::fixed()
4    => 2
5    >>> App\Lab\Lab::countedInSql()
6    => 1
7    >>> App\Lab\Lab::readTheSql()
8    => "select \"authors\".*, (select count(*) from \"books\" where ...) as \"books_count\" from \"authors\" where exists (...)"

Experiment 3: chunk skips rows, chunkById does not. Reset with UPDATE books SET in_stock = true; and then:

text
1    >>> App\Lab\Lab::chunkVisited()
2    => 2500     // not 5000: half the rows were skipped, no error
3    SELECT count(*) FROM books WHERE in_stock;   -- 2500 rows still true
4    UPDATE books SET in_stock = true;
5    >>> App\Lab\Lab::chunkByIdVisited()
6    => 5000
7    SELECT count(*) FROM books WHERE in_stock;   -- 0

The Go equivalents are chunk.OffsetSweep(ctx, db, 100) (visits fewer than 5,000) and chunk.KeysetSweep(ctx, db, 100) (visits 5,000).

Experiment 4: find the N+1 from the server side.

sql
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;  -- needs shared_preload_libraries
SELECT calls, round(mean_exec_time::numeric, 3) AS ms, query
FROM pg_stat_statements WHERE query ILIKE '%FROM books WHERE author_id%' ORDER BY calls DESC LIMIT 3;
-- one statement with calls = 200 per page view and ms near 0.05: that is the N+1

Experiment 5: bulk vs per-row. In tinker, time foreach (range(1, 5000) as $i) Book::create([...]) against Book::insert($rows) in batches of 1,000: expect seconds versus tens of milliseconds on a local container.

Common misconceptions ​

BeliefReality
"N+1 only matters at scale."It is a latency tax proportional to rows per page from the first release; it only becomes visible at scale
"Eager loading is a JOIN."In Eloquent and GORM Preload it is a second query with IN; Joins is the join form
"Eager loading is always faster."It trades round trips for memory; load only what you render and select columns
"chunk is safe for batch updates."It skips rows when the update changes the filter; use chunkById
"cursor() can eager load and uses no memory."It cannot eager load; the PDO driver may buffer all rows
"upsert is a better save()."It skips events, casts, mutators and observers and needs a unique index
"A bulk update fires model events."Mass update, insert, upsert and delete fire none
"My method is one transaction."Only if you wrote DB::transaction or BeginTx; otherwise each statement commits alone
"find(1) twice returns the same object."Not in Eloquent, GORM or Rails; only Data Mapper ORMs have an identity map
"The ORM prevents SQL injection."Only for bound values; raw strings and identifiers are yours to protect
"Soft delete is just a delete."The row stays in tables, indexes, unique constraints and backups
"A polymorphic relation has a foreign key."It cannot; orphans are possible
"timestamp stores a moment."timestamptz does; timestamp is a wall-clock reading
"Mocking the ORM tests the query."It tests the call; only a real database tests the SQL
"Auto-generated migrations are safe."They are mechanical: renames drop data, indexes lock, NOT NULL rewrites
"A repository makes the ORM swappable."Eloquent types usually leak through; the benefit is a seam and a place for query code

Cheat sheet ​

TopicWhat to remember
N+11 query for parents + 1 per parent; fix with with, Preload, a join, or withCount
Eloquent loaderswith, load, loadMissing, withCount, withSum, nested with('a.b'), with('a:id,name') keep key columns
StrictnessModel::shouldBeStrict(! app()->isProduction()); preventLazyLoading, handleLazyLoadingViolationUsing
GORMPreload, Joins (belongs-to/has-one), Preload(clause.Associations), Debug(), ToSQL, FindInBatches, CreateInBatches, default transaction per write
HydrationSelect columns, pluck, toBase, DTOs; models cost memory and CPU
Big tableschunkById / lazyById when updating; lazy read-only; cursor cannot eager load; offset skips
Bulkinsert (no events), upsert (unique index), insertOrIgnore (hides errors), mass update (no events, no updated_at)
Limits65,535 bind parameters (PostgreSQL, MySQL); batch 500-1,000 rows; unnest or COPY
TransactionsAutocommit by default; wrap use cases in DB::transaction; side effects after commit
IdentityEloquent and GORM: no identity map; Doctrine, Hibernate, SQLAlchemy: yes
Raw SQLBind values; whitelist identifiers; whereIntegerInRaw for int lists
Bad SQLHuge IN -> ANY(array)/join; OR chain -> IN/UNION; whereHas -> check plan; LIKE '%x%' -> trigram
Soft deletesPartial unique index WHERE deleted_at IS NULL; purge job
PolymorphicNo FK; enforceMorphMap; consider separate tables with CHECK
Timetimestamptz, store UTC, bulk writes skip timestamps
Optimistic lockVersion column and WHERE version = ?; check rows affected
Reading SQLtoRawSql, DB::listen, Debug(), pg_stat_statements, EXPLAIN (ANALYZE, BUFFERS)
TestsReal engine, query-count assertions, strict mode in test bootstrap

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A Blade view prints $author->books->count() for 50 authors. How many queries run, and name two fixes? Must-know ​

Answer

Answer: 51: one for the authors and one per author. Fix with Author::withCount('books') (then read books_count) or with('books'); guard the code path with Model::preventLazyLoading(). See N+1 and eager loading.

2 — Does Author::with('books') run a JOIN? Must-know ​

Answer

Answer: No. It runs a second query ... FROM books WHERE author_id IN (...) and groups the rows in PHP. A join is the Joins shape in GORM or JOIN FETCH in Doctrine. See preload or join.

3 — You narrow a relation with with('books:title') and the stitching breaks. Why? Important ​

Answer

Answer: The relation needs the key and foreign key columns to match books to authors; select id and author_id as well: with('books:id,author_id,title').

4 — A job flips in_stock = false using Book::where('in_stock', true)->chunk(200, ...) and finishes with rows still true. What happened and what do you change? Important ​

Answer

Answer: chunk pages with OFFSET; each update removed rows from the filter, so later offsets skipped unvisited rows. Use chunkById or lazyById, which page with WHERE id > last. See chunking.

5 — What does Book::where(...)->update([...]) skip compared with loading and saving each model? Important ​

Answer

Answer: Model events (saving, saved, updating, updated) and observers, casts and mutators, and the automatic updated_at; it is one atomic SQL statement. See bulk writes.

6 — Why can insertOrIgnore be dangerous? Important ​

Answer

Answer: It ignores duplicate-key errors and, depending on the engine, other errors; the Laravel docs note it bypasses MySQL strict mode. You cannot tell skipped rows from inserted ones. Prefer upsert or check the affected count.

7 — Your import of 10,000 rows crashes at row 6,000. How many rows are stored with a save() loop and without a transaction, and how do you make it all-or-nothing? Must-know ​

Answer

Answer: About 6,000: each save() autocommits. Wrap the batch in DB::transaction (or BeginTx in Go) so a crash rolls back everything, and batch with upsert or multi-row INSERT. See transactions.

8 — Why does Book::find(1) twice in Eloquent give two objects while Doctrine gives one? Good to know ​

Answer

Answer: Doctrine's EntityManager implements an Identity Map and a Unit of Work; Eloquent is Active Record with neither. See identity map and Active Record vs Data Mapper.

9 — Which of these is injectable: where('name', $x), whereRaw("name = '$x'"), orderBy($col) with user input, whereRaw('name = ?', [$x])? Must-know ​

Answer

Answer: The second and third. Values bound with ? are safe; concatenation is not, and column names cannot be bound, so whitelist them. See raw SQL.

10 — Why does a unique index on users.email break soft-deleted accounts re-signing up, and what fixes it in PostgreSQL? Important ​

Answer

Answer: The index still contains the soft-deleted row. Replace it with a partial unique index WHERE deleted_at IS NULL. See soft deletes.

11 — How would you spot an N+1 from the database side? Must-know ​

Answer

Answer: pg_stat_statements shows one normalised statement (... WHERE author_id = $1) with a very high calls count and a tiny mean time. In the application, DB::listen, db.Debug(), or query-count assertions. See reading the SQL.

12 — Why is mocking the ORM a poor substitute for a real database in tests? Important ​

Answer

Answer: A mock verifies calls, not SQL: it misses N+1, constraint violations, NULL and collation behaviour, engine-specific features and migrations. Use a real engine and query-count assertions. See testing.

Glossary ​

TermMeaning
ORMObject-relational mapper: a library that maps tables and rows to classes and objects
Impedance mismatchThe conceptual gap between an object graph and a relational schema (identity, relationships, inheritance, types)
N+1One query for N parents plus N queries for their relations
Lazy loadingFetching a relation on first property access
Eager loadingFetching relations in advance in a fixed number of queries
with / load / loadMissingEloquent: eager load before the query / on existing models / only if not loaded
withCount / withSumEloquent: add a subquery aggregate attribute (books_count, books_sum_price_cents)
Nested eager loadingwith('a.b.c'): one query per level
preventLazyLoadingEloquent guard that throws LazyLoadingViolationException on a lazy load
shouldBeStrictEloquent switch for preventLazyLoading, preventSilentlyDiscardingAttributes, preventAccessingMissingAttributes
automaticallyEagerLoadRelationshipsEloquent option that batches lazy loads across sibling models
HydrationTurning result rows into model objects
DTOData transfer object: a small plain struct for a read
chunkEloquent iteration with LIMIT/OFFSET; skips rows if the loop changes the filter
chunkById / lazyByIdIteration with WHERE id > last; safe when updating
lazychunk flattened into a LazyCollection
cursorOne query, one model at a time through a generator; cannot eager load
Keyset pagingWHERE key > last ORDER BY key LIMIT n; position by value, not by count
insertEloquent multi-row insert; no events, no timestamps
upsertInsert-or-update in one statement; needs a unique index on the key columns
insertOrIgnoreInsert that ignores duplicate (and possibly other) errors
Mass updateModel::where(...)->update(...): one UPDATE, no model events
Model eventssaving, saved, creating, updating and so on, fired by model operations
ObserverA class that listens to model events
saveQuietly / withoutEventsSave or run without firing model events
Implicit transactionThe transaction a database or ORM opens around a single statement or write
DB::transactionLaravel's explicit transaction boundary, with attempts retries
SkipDefaultTransactionGORM setting that removes its per-write transaction
Identity MapKeeps one object per row per session
Unit of WorkCollects changes and writes them at flush()
Active RecordThe model object persists itself (Eloquent, Rails, Django)
Data MapperA separate mapper persists plain objects (Doctrine, Hibernate, SQLAlchemy)
RepositoryA collection-like interface over the mapping layer
Query builderA fluent API that builds SQL without hydrating domain behaviour
Raw SQLSQL you write yourself; bind values, whitelist identifiers
SQL injectionUntrusted input becoming SQL text
whereIntegerInRawEloquent: inline an integer list instead of binding it
ANY(array)PostgreSQL predicate that takes one array parameter
Soft deleteMarking deleted_at instead of removing the row
Partial indexAn index with a WHERE; used to scope uniqueness to live rows
Polymorphic relationA relation whose foreign id may point at several tables, with no FK
enforceMorphMapEloquent: store short names instead of class names in morph type columns
timestamptzPostgreSQL timestamp that stores an instant
Optimistic lockingA version column checked in the WHERE of the update
AutoMigrateGORM schema sync; not a safe production migration tool
toRawSqlEloquent: the SQL with bindings substituted
DB::listenEloquent hook called for every executed statement
Debug / ToSQL / DryRunGORM ways to see or avoid running SQL
Preload / JoinsGORM: separate-query eager loading / LEFT JOIN loading
pgxPostgreSQL driver and toolkit for Go; CopyFrom, Batch, CollectRows
sqlxGo extensions over database/sql: struct scanning, named parameters, In
sqlcGenerates type-safe Go from SQL
EntGo entity framework with generated graph API and eager-loading edges
BunGo SQL-first ORM over database/sql
DoctrinePHP Data Mapper ORM with identity map, unit of work and DQL
pg_stat_statementsPostgreSQL extension of per-statement call counts and timings
TestcontainersLibrary that starts real database containers for tests

References ​

Built by Morteza Negahi