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 for | Go to |
|---|---|
| A table to memorise in a minute | Everything in one minute |
| Why ORMs hide cost, and the trade-off | Why ORM pitfalls exist |
| Fowler's vocabulary: Active Record, Data Mapper, Identity Map, Unit of Work, Lazy Load, Repository | Where the vocabulary comes from |
| One pitfall with a timeline and fixes in SQL, Go and Laravel | The pitfalls, one by one |
| Eloquent vs GORM vs pgx/sqlx/sqlc/Ent/Bun vs Doctrine/Hibernate/SQLAlchemy/Rails/Django | Per-ORM behaviour |
| Reading the SQL, knobs, error messages | Mechanics |
| Complete fixes: N+1, imports, sweeps, reports, tests | Solving the classic problems |
| Which tool for which operation | Choosing a tool |
| Monolith, microservices, replicas, scale | In architecture |
| Reproduce N+1 and the chunk skip | Lab |
| Wrong beliefs, cheat sheet, terms | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The pitfalls. Every row is unpacked in the pitfalls section.
| Pitfall | In plain words | Tiny example | The fix |
|---|---|---|---|
| N+1 / lazy loading | One query for the list, then one more per row | 25 books, $book->author in a loop = 26 queries | with('author'), Preload, a JOIN, withCount |
| Over-fetching and hydration cost | You load whole objects when the page needs two columns | Author::all() to print names | select(['id','name']), DTOs, pluck |
| Offset chunking while updating | The loop shifts the pages under itself | chunk() + update on the filtered column skips rows | chunkById, lazyById, keyset |
| Row-by-row writes | N statements, N round trips, N commits | save() in a loop of 10,000 | insert, upsert, one transaction, COPY |
| Bulk call skips behaviour | No events, no observers, no casts, no updated_at | Book::where(...)->update([...]) | Know the list; touch timestamps yourself |
| Implicit transaction | One write = one hidden transaction; a loop of writes is not atomic | 500 save() calls, crash at 300, 300 rows committed | DB::transaction, db.Transaction |
| No identity map | The same row loaded twice is two objects | Book::find(1) twice gives two instances; edits diverge | Pass the object, or use a Data Mapper ORM |
| Raw SQL concatenation | A string you built is a string an attacker can build | whereRaw("name = '$name'") | Bindings, ?, $1, whitelist identifiers |
| Bad generated SQL | The ORM is faithful, not clever | 5,000-element IN, 40-branch OR chain, whereHas on a large table | Temp table, ANY(array), join, rewrite |
| Soft deletes | "Deleted" rows still exist, still count, still collide | Unique email blocks re-signup | Partial unique index, deleted_at in indexes |
| Polymorphic relations | One column holds an id of different tables | commentable_id has no foreign key | Separate tables or accept and test the gap |
| Timestamps and time zones | Dates are strings with hidden zone rules | now() stored in app zone, read in another | Store UTC, timestamptz, one source of truth |
| ORM-generated migrations | The diff tool does not know your traffic | Rename column = drop + add | Review --pretend SQL, expand/contract |
The loaders. What each way of reading relations or rows costs.
| Method | Queries | Memory | Eager loading | Safe while updating filter columns |
|---|---|---|---|---|
Lazy property access ($a->books) | 1 + N | small per step | no | n/a |
with('books') / Preload("Books") | 2 | whole result set | yes | n/a |
Joins("Author") / JOIN FETCH | 1 | whole set, repeated parent columns | yes | n/a |
get() / Find | 1 | whole result set | optional | n/a |
chunk(n) | 1 per page, OFFSET | n models | yes | no |
chunkById(n) | 1 per page, WHERE id > | n models | yes | yes |
lazy(n) / lazyById(n) | like chunk / chunkById | n models, flat iterator | yes | lazyById yes |
cursor() | 1 | 1 model, but the driver may buffer | no | depends on the driver |
The bulk writers. What each one skips.
| Call | Statements | Model events | Casts, mutators | created_at / updated_at | Atomic |
|---|---|---|---|---|---|
$model->save() per row | N | fired | applied | set | each statement alone |
Model::where(...)->update([...]) | 1 | not fired | not applied | not touched | yes (one statement) |
Model::insert($rows) | 1 per batch | not fired | not applied | not set | per statement |
Model::upsert($rows, ...) | 1 per batch | not fired | not applied | updated_at set on update | per statement |
insertOrIgnore($rows) | 1 per batch | not fired | not applied | not set | per statement, hides errors |
DB::table(...)->... | 1 | no model at all | none | not set | per statement |
GORM Create(&slice) | 1 per batch | hooks run | applied | set (autoCreateTime) | wrapped in a transaction |
pgx CopyFrom | 1 COPY | none | none | none | whole 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:
| Side | You gain | You pay |
|---|---|---|
| Hide SQL behind objects (ORM) | Less code, rich model behaviour, portability, fewer typos | Statement 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 reports | More code, hand-written mapping, you own the injection discipline |
| Load everything eagerly | Few round trips | Big result sets, repeated parent columns in joins, wasted memory |
| Load lazily | Small steps, simple code | A 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
- "
$book->authoris a property read, so it is free." It looks like memory access and is a network round trip the first time. - "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.
- "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".
| Mismatch | Object side | Relational side | Where it bites |
|---|---|---|---|
| Identity | Two references can be the same or different objects | One primary key per row | No identity map in Eloquent: two instances of one row |
| Relationships | $author->books follows a pointer | books.author_id joined by a query | N+1 |
| Inheritance | class Admin extends User | Single table, table per class, or joined tables | Wide nullable tables, hard queries |
| Granularity | One Address value object | Several columns, or a table | Embedded vs related models |
| Navigation | Walk the graph | Ask a set question | Loops instead of joins |
| Types | DateTimeImmutable, enums | timestamptz, smallint, text | Time zones, casting, enums as strings |
| Writes | Mutate in memory, save later | Statement per change, transaction boundary | Silent 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:
| Pattern | Fowler'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.
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.
| Where | How the N+1 arises | Visible in code? |
|---|---|---|
| Eloquent | Reading a relation property that is not loaded | No: looks like a field |
| GORM | A db.Where(...).Find(...) inside a for loop; GORM has no lazy loading | Yes: a query call in a loop |
database/sql, pgx, sqlx | Same: a query call in a loop | Yes |
| Doctrine | Touching a lazy proxy or collection | No |
| Hibernate / JPA | Lazy @OneToMany or @ManyToOne(fetch=LAZY) | No |
| SQLAlchemy | Default lazy="select" | No |
| Rails ActiveRecord | Association without includes | No |
| Django | Foreign key access without select_related / prefetch_related | No |
Fix.
-- 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.
// 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.
// 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
// 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
// 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 call | When | What it sends |
|---|---|---|
Author::with('books')->get() | Before the parents are fetched | Parent query, then books WHERE author_id IN (...) |
$authors->load('books') | After you already have the models | Same second query, on the existing collection |
$author->loadMissing('books') | You are unsure if it is loaded | Loads only relations not yet present |
Author::withCount('books') | You need only a number | A correlated subquery; adds books_count |
Author::withSum('books', 'price_cents') | A sum, min, max, avg or exists | Adds books_sum_price_cents; also withMin, withMax, withAvg, withExists |
with('books:id,author_id,title') | You need only some columns | Narrow select; keep the key and foreign key |
with(['books' => fn ($q) => $q->where('in_stock', true)]) | You need a constrained relation | Extra WHERE on the second query |
Author::withWhereHas('books', fn ($q) => ...) | Filter parents by children and load the matches | EXISTS filter plus eager load |
Model::automaticallyEagerLoadRelationships() | You want the framework to batch for you | Loads the relation for all siblings on first access |
protected $with = ['author'] | A relation is always needed | Eager 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.
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 relationNested 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:
// 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:
// 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
}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?
| Approach | Queries | Duplicates parent columns | Good for | Limit |
|---|---|---|---|---|
Separate query (with, Preload, selectinload) | 1 per relation | no | has-many, deep graphs | IN list grows with parents |
JOIN (Joins, joinedload, JOIN FETCH) | 1 | yes | belongs-to, has-one, filters on the child | has-many multiplies rows, breaks LIMIT on the parent |
Subquery count (withCount) | 1 | no | numbers only | one 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
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());
}
}| Check | Throws when | Exception |
|---|---|---|
preventLazyLoading | A relation is lazy loaded | LazyLoadingViolationException |
preventSilentlyDiscardingAttributes | fill() / create() gets a key not in $fillable | MassAssignmentException |
preventAccessingMissingAttributes | You read an attribute that was not selected or does not exist | MissingAttributeException |
| Environment | Recommended setting | Why |
|---|---|---|
| Local, CI | shouldBeStrict() | N+1 becomes a red test |
| Staging | shouldBeStrict() with real data volume | Sees the shapes production sees |
| Production | preventLazyLoading() with handleLazyLoadingViolationUsing logging | Visibility 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 shape | Cost | Use when |
|---|---|---|
Book::all() | All columns, one model per row, dirty tracking | Rarely |
Book::select(['id','title'])->get() | Fewer bytes, still models | You need models but few columns |
DB::table('books')->get() | stdClass rows, no casts, no events | Read-only lists |
Book::pluck('title', 'id') | An array, no models | Dropdowns, id lists |
Book::toBase()->get() | Query builder rows from an Eloquent query | Keep scopes, skip hydration |
Book::query()->value('title') / exists() / count() | One scalar | Presence and counts |
GORM Select("id", "title").Find(&dtos) into a small struct | Fewer columns, no model | Read-only lists |
sqlc generated row struct | Exactly the selected columns | Typed reads |
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 timeReal 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.
-- 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.)
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| Method | Paging | Memory | Eager loading | Safe when updating the filter | Notes |
|---|---|---|---|---|---|
chunk | OFFSET | n models | yes | no | Offset also gets slower deep into the table |
chunkById | WHERE id > | n models | yes | yes | Needs a unique, ordered key; adds its own where, so group your own conditions in a closure |
lazy | OFFSET | n models, iterator | yes | no | chunk with a flat API |
lazyById | WHERE id > | n models, iterator | yes | yes | lazyByIdDesc for descending |
cursor | one query | 1 model | no | depends | The Laravel docs say it "cannot eager load relationships"; PDO may still buffer all rows, so it "will still eventually run out of memory" |
each | chunk | n models | yes | no | each(fn) on the builder is chunk-then-foreach |
GORM FindInBatches | keyset by primary key | n structs | Preload works | yes | Pages by primary key |
database/sql Rows | one query | 1 row | n/a | depends | Needs 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:
// 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()
}-- 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.
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| Operation | Eloquent | GORM | pgx / SQL | Events skipped |
|---|---|---|---|---|
| Insert many | Book::insert($rows) | db.Create(&slice) (single statement; hooks still run) / CreateInBatches(rows, 100) | multi-row VALUES, unnest, CopyFrom | Eloquent: yes; GORM: no |
| Insert, ignore duplicates | insertOrIgnore($rows) | Clauses(clause.OnConflict{DoNothing: true}) | ON CONFLICT DO NOTHING | Eloquent: yes |
| Insert or update | Book::upsert($rows, ['sku'], ['title']) | Clauses(clause.OnConflict{UpdateAll: true}) | ON CONFLICT (sku) DO UPDATE / MySQL ON DUPLICATE KEY UPDATE | Eloquent: yes |
| Update many | Book::where(...)->update([...]) | db.Model(&Book{}).Where(...).Updates(...) | UPDATE ... WHERE | Eloquent: yes |
| Delete many | Book::where(...)->delete() | db.Where(...).Delete(&Book{}) | DELETE ... WHERE | Eloquent: yes |
| Bulk load | insertUsing, raw COPY | CopyFrom via pgx | COPY books FROM STDIN | n/a |
| Per-row | $book->save() | db.Save(&book) | UPDATE ... WHERE id | no |
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.
// 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
// 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 update | Per-row save() | |
|---|---|---|
| Statements | 1 | 1 SELECT + N UPDATE |
| Events and observers | not fired | fired |
| Casts, mutators | not applied | applied |
updated_at | not touched | set |
Dirty tracking (isDirty, wasChanged) | no model | works |
| Lock duration | one statement, may lock many rows at once | short per row |
| Race with another writer | one atomic SET x = x * 0.9 | read-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.
-- 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.
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 shownThree 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.
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: 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
})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."
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 UPDATEReal 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.
| ORM | Identity map | Unit of Work | Dirty tracking |
|---|---|---|---|
| Eloquent | no | no (explicit save) | per model (isDirty) |
| GORM | no | no | Save writes all fields; Updates writes given fields |
| Doctrine ORM | yes (EntityManager) | yes (flush) | automatic, by snapshot comparison |
| Hibernate / JPA | yes (session) | yes (flush) | automatic |
| SQLAlchemy ORM | yes (Session) | yes | automatic |
| Rails ActiveRecord | per-request query cache only | no | per model |
| Django | no | no | save() writes all fields unless update_fields |
| Ent | no | no | explicit 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.
| Pitfall | Why it happens | Fix |
|---|---|---|
| Cached model carries an unloaded relation | Lazy load after unserialize runs a query or throws under strictness | Cache arrays or DTOs, not models |
| Bulk update leaves cache stale | update() fires no updated event, so the observer that clears the cache does not run | Invalidate in the same code path, or version the key |
| Stampede | Many requests miss together and all query | Cache::lock, remember with jitter, stale-while-revalidate |
| Write-then-read from a replica | The cache fills from a stale replica | Read primary after write, see Replication |
| Cache written before commit | Reader sees data that is rolled back | Write the cache in DB::afterCommit |
| Cache inside the transaction | Lost update through the cache | Delete the key after commit, do not rewrite it; see Isolation Levels |
// 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.
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)| Technique | Safe? | Note |
|---|---|---|
where('col', $value) | yes | Binding |
whereRaw('lower(name) = ?', [$v]) | yes | Binding in raw |
whereRaw("lower(name) = '$v'") | no | Concatenation |
orderBy($col) with user input | no | Whitelist the column |
DB::unprepared($sql) | no | The docs: "never allow user controlled values" |
whereIntegerInRaw('id', $ids) | yes if the values are cast to int | Inlines integers on purpose to save memory |
GORM Where("name = ?", v) | yes | Binding |
GORM Where("name = '" + v + "'") | no | Concatenation |
database/sql $1 / ? | yes | Server-side or driver-side binding |
| sqlc generated functions | yes | Parameters 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.
-- the dynamic part: validated column, bound value
SELECT id, title FROM books WHERE title ILIKE $1 ORDER BY created_at DESC LIMIT 20;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+"%")
}$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.
| Shape | Produced by | Problem | Fix |
|---|---|---|---|
IN with thousands of ids | whereIn('id', $ids) after a big pluck | Long parse, parameter limit (65,535), a plan per distinct list length | Join on a temp table, = ANY($1) with one array, whereIntegerInRaw, chunk the ids |
Long OR chain | A loop adding orWhere | PostgreSQL can combine with BitmapOr; MySQL may fall to a scan; plan time grows | IN, UNION ALL, a join on VALUES |
OR across columns | where('a', 1)->orWhere('b', 1) | One index cannot serve both | Two queries UNIONed, or an index per column and rely on bitmap-or |
whereHas | Nested EXISTS | Correlated subquery per parent; slow on big tables | join with distinct, or whereIn on a subquery, check the plan |
count(*) for pagination | paginate() | Counts the whole filtered set on every page | simplePaginate, cursorPaginate, cached or estimated count; see Pagination |
OFFSET deep pages | paginate(), chunk | Reads and discards offset rows | Keyset |
SELECT * | default | Wide rows, no index-only scan | Select columns |
LIKE '%x%' | where('name', 'like', "%$x%") | Cannot use a B-tree | pg_trgm GIN or full-text; see Full-Text Search |
| Function on an indexed column | whereRaw('lower(email) = ?'), whereDate('created_at', $d) | Index not used | Expression index, range predicate |
| N sorts | orderBy on a computed alias | Sort in memory | Index matching the order |
| Casting mismatch | Binding a string against an int column | Implicit cast defeats index | Cast in the application |
| Prepared-statement plan flip | PDO::ATTR_EMULATE_PREPARES off, generic plan | PostgreSQL may choose a generic plan after five executions | plan_cache_mode, see Query Planning |
-- 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.
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 rowsSoft 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.
| Issue | Why | Fix |
|---|---|---|
| Unique collision | email unique index includes deleted rows | PostgreSQL partial unique index WHERE deleted_at IS NULL; MySQL: unique on (email, deleted_at) or a generated column |
| Slow queries | The hidden predicate is not in your index | Include deleted_at IS NULL in a partial index on hot paths |
| Table bloat | Deleted rows never leave | Purge job with chunkById + forceDelete; archive; partition by date |
| Foreign keys | A child references a soft-deleted parent | Cascade soft delete in the model, or hard delete children |
Raw queries and JOINs | Global scope applies only to model queries | Add the predicate to every raw query and to joins |
| Counts | withCount counts deleted children unless scoped | withCount(['books' => fn ($q) => ...]); the relation's scope applies |
unique validation | Rule sees deleted rows | Rule::unique(...)->withoutTrashed() |
| Privacy | Data is retained | Hard delete or anonymise on request |
-- 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;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.
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| Problem | Effect | Fix |
|---|---|---|
| No foreign key | Orphan rows after delete | Delete in model events or a job; a periodic orphan query; or avoid polymorphism |
| Class name in the type column | Renaming a class breaks data | Relation::enforceMorphMap(['book' => Book::class]) |
| Eager loading across types | One query per type | morphWith for nested relations; accept one query per type |
| Index | (commentable_type, commentable_id) is needed | morphs() creates the composite index |
| Query for all comments of authors and books | Hard in SQL | Separate 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.
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.
| Pitfall | Example | Fix |
|---|---|---|
| Local time stored | App zone Asia/Tehran, a second service in UTC reads the same column | Store UTC, convert at the edge |
timestamp without time zone | PostgreSQL timestamp loses the offset | timestamptz (Laravel timestampTz) |
Bulk write leaves updated_at | update() or insert() skips timestamps | Set them in the statement ('updated_at' => now()) |
| Clock skew | Two app servers differ by seconds | Use the database's now() for ordering, or a sequence |
now() inside a transaction | PostgreSQL now() is the transaction start time | clock_timestamp() if you need wall time |
| Daylight saving | Add 24 hours vs "same wall time tomorrow" | Do date math in UTC |
whereDate('created_at', $d) | Function on the column kills the index | whereBetween('created_at', [$start, $end]) |
| Casts | 'immutable_datetime' vs datetime | Prefer immutable casts, avoid in-place ->addDay() mutation |
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.
| ORM | Built-in version check | How |
|---|---|---|
| Hibernate / JPA | yes | @Version; OptimisticLockException |
| Doctrine ORM | yes | #[Version] or LockMode::OPTIMISTIC; OptimisticLockException |
| Rails | yes | lock_version column; StaleObjectError |
| Django | no (third-party) | F() expressions, select_for_update |
| Eloquent | no | where('version', $v)->update([... 'version' => $v + 1]) and check affected rows |
| GORM | plugin | gorm.io/plugin/optimisticlock Version field; or manual Where("version = ?") and RowsAffected |
| Ent | no | Hand-written predicate, UpdateOne(...).Where(...) |
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$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.
| Danger | What the diff emits | Production-safe version |
|---|---|---|
| Rename column | DROP COLUMN + ADD COLUMN (data lost) | RENAME COLUMN, or expand/contract with dual writes |
New NOT NULL column | ADD COLUMN ... NOT NULL DEFAULT | Add nullable, backfill in batches, then SET NOT NULL via a validated CHECK |
| New index | CREATE INDEX | CREATE INDEX CONCURRENTLY (PostgreSQL), online DDL (MySQL) |
| New foreign key | ADD FOREIGN KEY | NOT VALID then VALIDATE CONSTRAINT |
| Change column type | ALTER COLUMN TYPE | New column, backfill, switch, drop |
AutoMigrate at startup (GORM) | Runs DDL on every deploy, from every pod | Run migrations as a separate job; never from the web process |
| Down migrations | Not tested | Forward-only fixes |
| Foreign key without index (PostgreSQL) | Missing index on the referencing column | Add 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.
| Question | Active Record | Data Mapper |
|---|---|---|
| Where does persistence live | On the model | In a mapper / entity manager |
| Domain object knows SQL | Yes (inherits Model) | No |
| Identity map, unit of work | No | Yes |
| Testing the domain without a database | Hard | Easy |
| Boilerplate | Low | Higher |
| Surprise | Hidden queries on property access | Hidden queries on flush() and lazy proxies |
| Typical pitfall | N+1, bulk bypasses events | Flush order, stale entities after clear(), proxy initialisation |
| Fits | CRUD apps, admin tools, startups | Rich 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
| Product | Model | Relation loading | N+1 guard | Bulk | Notes |
|---|---|---|---|---|---|
| Eloquent (Laravel 13) | Active Record | Lazy by default; with, load, withCount | preventLazyLoading, shouldBeStrict, automaticallyEagerLoadRelationships | insert, upsert, insertOrIgnore, mass update | No identity map; chunk APIs |
| GORM | Active-Record-style over structs | No lazy loading; Preload, Joins | none: a query in a loop is the bug | Create(&slice), CreateInBatches, Clauses(OnConflict), FindInBatches | Default transaction per write; hooks; soft delete via DeletedAt |
database/sql + pgx | None | You write every query | none | pgx.Batch, CopyFrom, unnest | Full control; rows.Close() discipline |
| sqlx | Thin: struct scanning and named parameters | You write every query | none | NamedExec with a slice, sqlx.In | Select, Get, StructScan; no relations |
| sqlc | Code generation from SQL | You write the join or the IN | none; 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 |
| Ent | Data-Mapper-style, generated graph API | WithPosts()-style eager loading, separate queries | none, but loading is explicit | CreateBulk, OnConflict | Schema as Go code, code generation |
| Bun | Query builder + models | Relation("Author") joins for has-one and uses separate queries for has-many | none | NewInsert().Model(&slice), On("CONFLICT"), bun.In | bundebug query hook prints SQL |
| Doctrine ORM (PHP) | Data Mapper | Lazy proxies, EXTRA_LAZY, JOIN FETCH in DQL | none built in; $em->getUnitOfWork() inspectable | DQL UPDATE/DELETE, batch with flush()+clear() | Identity map, unit of work, #[Version] |
| Hibernate / JPA | Data Mapper | Lazy by default for collections; @EntityGraph, JOIN FETCH, @BatchSize | LazyInitializationException after close | JDBC batching (hibernate.jdbc.batch_size) | Second-level cache |
| SQLAlchemy | Data Mapper + Core | selectinload, joinedload, lazy="raise" | lazy="raise" | insert().values([...]), bulk_insert_mappings | Identity map in Session |
| Rails ActiveRecord | Active Record | includes, preload, eager_load | strict_loading, bullet gem | insert_all, upsert_all, update_all | lock_version optimistic locking |
| Django ORM | Active Record | select_related, prefetch_related | none built in | bulk_create, bulk_update, update() | QuerySet is lazy until iterated |
GORM, sqlx, pgx, sqlc, Ent and Bun in Go, in practice:
// 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)// 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...)// 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)// 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.
| Tool | What it shows | How |
|---|---|---|
Eloquent toSql() / toRawSql() | The statement, with ? or with bindings filled in | Book::where(...)->toRawSql() |
Eloquent dumpRawSql() / ddRawSql() | Same, printed in the request | Chain on the builder |
DB::listen | Every statement after it runs: $query->sql, $query->bindings, $query->time (ms), $query->toRawSql() | In a service provider |
DB::enableQueryLog() / DB::getQueryLog() | An in-memory list | Tests and tinker |
DB::pretend(fn) | The statements a closure would run, without running them | php artisan migrate --pretend |
| Laravel Telescope, Debugbar, Pulse | Per-request query list, duplicates, slow queries | Install in non-production |
GORM db.Debug() | Logs each statement with duration and rows | db.Debug().Find(&x) |
GORM db.ToSQL(fn) and DryRun: true | SQL without executing | tx.Statement.SQL.String() |
| GORM logger | logger.Default.LogMode(logger.Info), SlowThreshold | gorm.Config{Logger: ...} |
pgx tracelog / QueryTracer | Statements with arguments and timing | pgx.ConnConfig.Tracer |
database/sql db.Stats() | Pool counters | OpenConnections, WaitCount; see Connection Pooling |
PostgreSQL log_min_duration_statement | Slow statements in the server log | ALTER SYSTEM SET log_min_duration_statement = '200ms' |
pg_stat_statements | Calls, mean time and rows per normalised statement | A statement with calls in the millions and tiny mean_exec_time is an N+1 |
auto_explain | Plans of slow statements in the log | auto_explain.log_min_duration |
MySQL slow query log, performance_schema | Same | long_query_time |
EXPLAIN (ANALYZE, BUFFERS) | The plan; see Query Planning | Paste the toRawSql() output |
// 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
| Knob | Product | Effect |
|---|---|---|
Model::preventLazyLoading($bool) | Laravel | Throw on lazy load |
Model::shouldBeStrict($bool) | Laravel | Three checks at once |
Model::preventSilentlyDiscardingAttributes() | Laravel | Throw instead of dropping unfillable attributes |
Model::preventAccessingMissingAttributes() | Laravel | Throw on unselected attributes |
Model::automaticallyEagerLoadRelationships() | Laravel | Batch lazy loads of siblings |
Model::handleLazyLoadingViolationUsing(fn) | Laravel | Log instead of throw |
protected $with, $withCount | Laravel | Always eager load |
$fillable, $guarded, Model::unguard() | Laravel | Mass-assignment policy |
PDO::ATTR_EMULATE_PREPARES | PHP PDO | Client-side vs server-side prepare |
SkipDefaultTransaction | GORM | Remove the per-write transaction |
PrepareStmt | GORM | Cache prepared statements per connection |
DryRun, Logger, NowFunc | GORM | Debugging and clock control |
CreateBatchSize | GORM | Default batch for Create(&slice) |
SetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime | database/sql | Pool limits; a loop of N queries holds one connection |
jdbc.batch_size, fetch_size | Hibernate | Statement batching, streaming |
plan_cache_mode, max_prepared_transactions, statement_timeout, idle_in_transaction_session_timeout | PostgreSQL | Plan reuse, timeouts for runaway ORM loops |
max_allowed_packet, max_prepared_stmt_count | MySQL | Limits for giant INSERTs |
Error messages you will meet Must-know
| Message | Product | Meaning | Fix |
|---|---|---|---|
Attempted to lazy load [books] on model [App\Models\Author] but lazy loading is disabled. (LazyLoadingViolationException) | Laravel | preventLazyLoading caught a lazy load | Add with |
The attribute [x] either does not exist or was not retrieved for model [...] (MissingAttributeException) | Laravel | You narrowed select and read a missing column | Select it |
Add [x] to fillable property to allow mass assignment on [...] (MassAssignmentException) | Laravel | create($request->all()) with an unfillable key | $fillable |
Allowed memory size of ... bytes exhausted | PHP | all() or eager loading too much | chunkById, lazy, select columns |
SQLSTATE 23505 duplicate key value violates unique constraint / MySQL 1062 | PostgreSQL / MySQL | Unique violation; soft-deleted row counts | Partial unique index; upsert |
| SQLSTATE 40001 / 40P01 / MySQL 1213 | PostgreSQL / MySQL | Serialization failure or deadlock | Retry the whole transaction; see Deadlocks |
number of parameters must be between 0 and 65535 (pgx: extended protocol limited to 65535 parameters) | PostgreSQL / pgx | Multi-row insert too big | Batch, unnest, COPY |
MySQL 1390 Prepared statement contains too many placeholders | MySQL | Same | Batch |
WHERE conditions required (gorm.ErrMissingWhereClause) | GORM | Delete/Update with no condition | Add a condition |
record not found (gorm.ErrRecordNotFound) | GORM | First, Take, Last found nothing | Check with errors.Is |
sql: Rows are closed, pool exhaustion context deadline exceeded | database/sql | Forgot rows.Close() or a long loop holds connections | defer rows.Close(); see Connection Pooling |
LazyInitializationException | Hibernate | Touched a lazy proxy after the session closed | JOIN FETCH, DTOs |
Solving the classic problems
N+1 in a list endpoint
| Solution | How | Advantage | Cost / limit |
|---|---|---|---|
with / Preload / selectinload | Second query with IN | Simple, works for has-many | Result set in memory; big IN |
withCount / withSum | Subquery per aggregate | No child rows loaded | One subquery per aggregate |
JOIN | One statement | One round trip | Duplicates parent columns; breaks LIMIT on parent |
| DTO query (raw / sqlc) | You write the exact shape | Minimal data | More code |
preventLazyLoading in CI | Fail on lazy load | Catches regressions | Only paths that tests execute |
| DataLoader (GraphQL) | Batch per request tick | Fixes resolver N+1 | Needs a batching layer |
| Denormalised counter column | books_count maintained on write | Reads become free | Write complexity, drift |
Code: N+1 section and eager loading.
Importing a file of 1,000,000 rows
| Solution | How | Advantage | Cost / limit |
|---|---|---|---|
Per-row save() | Loop | Events and validation | Hours; one commit per row |
Batched insert / upsert in one transaction | 500-1,000 rows per statement | 50 to 500 times faster | No events; validation is yours |
Staging table + INSERT ... SELECT | Load raw, transform in SQL | Set-based, restartable | Extra table |
COPY (pgx CopyFrom) | Wire protocol bulk | Fastest | No ON CONFLICT; whole load fails on one bad row |
| Queue per chunk | One job per 1,000 rows | Parallel, retryable | Idempotency required; see Idempotent Consumer |
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.
-- 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.
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.
| Approach | Catches | Misses | Speed |
|---|---|---|---|
| Mocks / fakes of the ORM | Control flow | Everything about SQL | Fastest |
| SQLite in memory (Laravel default for tests) | Basic logic | PostgreSQL-specific features: ON CONFLICT, jsonb, partial indexes, timestamptz, locking | Fast |
| Real PostgreSQL / MySQL in a container (Testcontainers, Docker Compose) | SQL, constraints, migrations, plans | Production-scale data | Seconds to start |
Transaction rollback per test (RefreshDatabase, DatabaseTransactions; Go: BEGIN/ROLLBACK) | Isolation between tests | Code that commits or uses multiple connections | Fast |
| Query-count assertions | N+1 regressions | Slow single queries | Fast |
EXPLAIN in CI on key queries | Missing index regressions | Data-dependent plans | Medium |
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).
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()));
}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
| Operation | Recommended tool | Extra technique | Reason |
|---|---|---|---|
| Single-entity create/update with rules | Model (save, GORM Save) | Observers, validation, transaction | Behaviour lives on the model |
| List with relations | with / Preload | Select columns, preventLazyLoading | Fixed query count |
| Counts and sums of children | withCount, withSum | Cached counter if hot | No child rows loaded |
| Filter parents by children | whereHas or JOIN | Check the plan | EXISTS vs join choice depends on data |
| Dynamic search filters | Query builder | Bindings, whitelisted columns | Composable and safe |
| Reports and analytics | Raw SQL / sqlc | EXPLAIN, replica, materialised view | The planner needs the whole shape |
| Walk a big table with updates | chunkById, lazyById, keyset | Commit per batch | No skipped rows |
| Read-only pass over a big table | lazy or cursor | select columns | Constant memory |
| Bulk import | Batched upsert in one transaction, or COPY | Staging table | Statement count |
| Bulk change needing events | chunkById + save | Queue the heavy part | Events are the reason |
| Money, stock, balances | Atomic UPDATE, FOR UPDATE, version column | Idempotency keys | Not read-modify-write; see Isolation Levels |
| Hot path in Go | pgx or sqlc | Prepared statements | Exact SQL, typed rows |
| Rich domain in PHP or Java | Data Mapper (Doctrine, Hibernate) | Repository per aggregate | Identity 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.
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 updateDistributed 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×
| Load | ORM-level concern | What to do |
|---|---|---|
| 1× (a few hundred rows per list) | N+1 is invisible | Turn 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 minutes | with everywhere, cursorPaginate, chunkById, indexes on foreign keys, pg_stat_statements in review |
| 100× | Hydration cost, connection pool pressure, bulk write contention, replica lag | DTO 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.
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-- 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.
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 21Experiment 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
// 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
// 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
// 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;
}
}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:
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; -- 0The 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.
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+1Experiment 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
| Belief | Reality |
|---|---|
| "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
| Topic | What to remember |
|---|---|
| N+1 | 1 query for parents + 1 per parent; fix with with, Preload, a join, or withCount |
| Eloquent loaders | with, load, loadMissing, withCount, withSum, nested with('a.b'), with('a:id,name') keep key columns |
| Strictness | Model::shouldBeStrict(! app()->isProduction()); preventLazyLoading, handleLazyLoadingViolationUsing |
| GORM | Preload, Joins (belongs-to/has-one), Preload(clause.Associations), Debug(), ToSQL, FindInBatches, CreateInBatches, default transaction per write |
| Hydration | Select columns, pluck, toBase, DTOs; models cost memory and CPU |
| Big tables | chunkById / lazyById when updating; lazy read-only; cursor cannot eager load; offset skips |
| Bulk | insert (no events), upsert (unique index), insertOrIgnore (hides errors), mass update (no events, no updated_at) |
| Limits | 65,535 bind parameters (PostgreSQL, MySQL); batch 500-1,000 rows; unnest or COPY |
| Transactions | Autocommit by default; wrap use cases in DB::transaction; side effects after commit |
| Identity | Eloquent and GORM: no identity map; Doctrine, Hibernate, SQLAlchemy: yes |
| Raw SQL | Bind values; whitelist identifiers; whereIntegerInRaw for int lists |
| Bad SQL | Huge IN -> ANY(array)/join; OR chain -> IN/UNION; whereHas -> check plan; LIKE '%x%' -> trigram |
| Soft deletes | Partial unique index WHERE deleted_at IS NULL; purge job |
| Polymorphic | No FK; enforceMorphMap; consider separate tables with CHECK |
| Time | timestamptz, store UTC, bulk writes skip timestamps |
| Optimistic lock | Version column and WHERE version = ?; check rows affected |
| Reading SQL | toRawSql, DB::listen, Debug(), pg_stat_statements, EXPLAIN (ANALYZE, BUFFERS) |
| Tests | Real engine, query-count assertions, strict mode in test bootstrap |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| ORM | Object-relational mapper: a library that maps tables and rows to classes and objects |
| Impedance mismatch | The conceptual gap between an object graph and a relational schema (identity, relationships, inheritance, types) |
| N+1 | One query for N parents plus N queries for their relations |
| Lazy loading | Fetching a relation on first property access |
| Eager loading | Fetching relations in advance in a fixed number of queries |
with / load / loadMissing | Eloquent: eager load before the query / on existing models / only if not loaded |
withCount / withSum | Eloquent: add a subquery aggregate attribute (books_count, books_sum_price_cents) |
| Nested eager loading | with('a.b.c'): one query per level |
preventLazyLoading | Eloquent guard that throws LazyLoadingViolationException on a lazy load |
shouldBeStrict | Eloquent switch for preventLazyLoading, preventSilentlyDiscardingAttributes, preventAccessingMissingAttributes |
automaticallyEagerLoadRelationships | Eloquent option that batches lazy loads across sibling models |
| Hydration | Turning result rows into model objects |
| DTO | Data transfer object: a small plain struct for a read |
chunk | Eloquent iteration with LIMIT/OFFSET; skips rows if the loop changes the filter |
chunkById / lazyById | Iteration with WHERE id > last; safe when updating |
lazy | chunk flattened into a LazyCollection |
cursor | One query, one model at a time through a generator; cannot eager load |
| Keyset paging | WHERE key > last ORDER BY key LIMIT n; position by value, not by count |
insert | Eloquent multi-row insert; no events, no timestamps |
upsert | Insert-or-update in one statement; needs a unique index on the key columns |
insertOrIgnore | Insert that ignores duplicate (and possibly other) errors |
| Mass update | Model::where(...)->update(...): one UPDATE, no model events |
| Model events | saving, saved, creating, updating and so on, fired by model operations |
| Observer | A class that listens to model events |
saveQuietly / withoutEvents | Save or run without firing model events |
| Implicit transaction | The transaction a database or ORM opens around a single statement or write |
DB::transaction | Laravel's explicit transaction boundary, with attempts retries |
SkipDefaultTransaction | GORM setting that removes its per-write transaction |
| Identity Map | Keeps one object per row per session |
| Unit of Work | Collects changes and writes them at flush() |
| Active Record | The model object persists itself (Eloquent, Rails, Django) |
| Data Mapper | A separate mapper persists plain objects (Doctrine, Hibernate, SQLAlchemy) |
| Repository | A collection-like interface over the mapping layer |
| Query builder | A fluent API that builds SQL without hydrating domain behaviour |
| Raw SQL | SQL you write yourself; bind values, whitelist identifiers |
| SQL injection | Untrusted input becoming SQL text |
whereIntegerInRaw | Eloquent: inline an integer list instead of binding it |
ANY(array) | PostgreSQL predicate that takes one array parameter |
| Soft delete | Marking deleted_at instead of removing the row |
| Partial index | An index with a WHERE; used to scope uniqueness to live rows |
| Polymorphic relation | A relation whose foreign id may point at several tables, with no FK |
enforceMorphMap | Eloquent: store short names instead of class names in morph type columns |
timestamptz | PostgreSQL timestamp that stores an instant |
| Optimistic locking | A version column checked in the WHERE of the update |
AutoMigrate | GORM schema sync; not a safe production migration tool |
toRawSql | Eloquent: the SQL with bindings substituted |
DB::listen | Eloquent hook called for every executed statement |
Debug / ToSQL / DryRun | GORM ways to see or avoid running SQL |
Preload / Joins | GORM: separate-query eager loading / LEFT JOIN loading |
pgx | PostgreSQL driver and toolkit for Go; CopyFrom, Batch, CollectRows |
sqlx | Go extensions over database/sql: struct scanning, named parameters, In |
sqlc | Generates type-safe Go from SQL |
| Ent | Go entity framework with generated graph API and eager-loading edges |
| Bun | Go SQL-first ORM over database/sql |
| Doctrine | PHP Data Mapper ORM with identity map, unit of work and DQL |
pg_stat_statements | PostgreSQL extension of per-statement call counts and timings |
| Testcontainers | Library that starts real database containers for tests |
References
- Laravel 13.x, Eloquent: Relationships: Eager Loading, Preventing Lazy Loading, Automatic Eager Loading
- Laravel 13.x, Eloquent: Strictness, Chunking Results, Cursors, Mass Updates, Upserts, Muting Events
- Laravel 13.x: Query Builder, Database (
DB::listen) - Laravel 13.x source:
Eloquent/Model.php,Concerns/BuildsQueries.php - GORM: Preloading, Transactions, Create, Hooks, Delete
- Martin Fowler, Patterns of Enterprise Application Architecture catalogue: Active Record, Data Mapper, Identity Map, Unit of Work, Lazy Load, Repository; bliki: OrmHate
- sqlc: Documentation; Ent: Eager Loading; Bun: Relations; Doctrine ORM: Working with Objects
- pgx v5:
pgx; Go:database/sql - PostgreSQL: 9.26.3 ANY/SOME (array)