Skip to content

دام‌های ORM: N+1، lazy loading و عملیات bulk ​

"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"

خلاصه: ORM رابطه‌ها را به property و نوشتن را به فراخوانی متد تبدیل می‌کند و هر کدام SQL را پنهان می‌کند؛ دام‌ها یعنی statement هایی که نمی‌دانستید فرستاده می‌شوند، ردیف‌هایی که نمی‌دانستید بارگذاری می‌شوند، و قاعده‌هایی (event، transaction، timestamp) که یک فراخوانی bulk بی‌صدا نادیده می‌گیرد. تمرکز: N+1 و eager loading، هزینهٔ hydration، تفاوت chunk و chunkById و lazy و cursor، نوشتن bulk (insert و upsert و update)، مرز transaction، Active Record در برابر Data Mapper، raw SQL و injection، SQL بدِ تولیدشده، و تفاوت Eloquent، GORM، pgx، sqlx، sqlc، Ent، Bun و Doctrine. هدف یادگیری: بتوانید SQL ای را که یک فراخوانی ORM می‌فرستد بخوانید، تعداد statement و حافظهٔ یک مسیر کد را پیش‌بینی کنید، و برای هر عملیات ابزار درست (model، query builder یا raw SQL) را انتخاب کنید.

این صفحه مرجع کامل اشتباهاتی است که با نگاشت شیء-رابطه‌ای (Object-Relational Mapper یا ORM) در production رخ می‌دهد: ناهمخوانی شیء-رابطه‌ای (Impedance Mismatch) که ریشهٔ آن‌هاست، پنجرهٔ پرسش‌های N+1، eager loading در همهٔ شکل‌هایش (with، load، loadMissing، withCount، withSum، nested eager loading، و Preload و Joins در GORM)، محافظ‌های lazy loading (preventLazyLoading، shouldBeStrict)، انتخاب ستون و هزینهٔ hydration، چهار راه پیمایش جدول بزرگ (chunk، chunkById، lazy، cursor)، نوشتن bulk (insert، upsert، insertOrIgnore، mass update در برابر save تک‌ردیفی) و eventهایی که رد می‌کنند، transaction ضمنی، نبود identity map، دام‌های caching، raw SQL و injection، SQL بد، soft delete، رابطه‌های polymorphic، timestamp و time zone، optimistic locking، migration های تولیدشده توسط ORM، و راه خواندن و تست آنچه ORM می‌فرستد. مباحث همسایه را دوباره درس نمی‌دهد: transaction در ACID & Transactions، anomalyها در Isolation Levels، مصالحهٔ offset و keyset در Pagination، ستون version در Optimistic vs Pessimistic Locking، خواندن plan در Query Planning، طراحی index در Indexing، cursor سمت سرور در Cursors & Streaming، اندازهٔ pool در Connection Pooling، ایمنی migration در Zero-Downtime Schema Migrations و injection در عمق در Database Security.

نقشهٔ صفحه ​

اگر دنبال این هستیدبه این بخش بروید
جدولی که در یک دقیقه حفظ شودهمه‌چیز در یک دقیقه
چرا ORM ها هزینه را پنهان می‌کنند و مصالحه چیستچرا دام‌های ORM وجود دارند
واژگان Fowler: Active Record، Data Mapper، Identity Map، Unit of Work، Lazy Load، Repositoryواژگان از کجا آمده‌اند
یک دام با timeline و راه‌حل در SQL و Go و Laravelدام‌ها، یکی‌یکی
Eloquent، GORM، pgx/sqlx/sqlc/Ent/Bun و Doctrine/Hibernate/SQLAlchemy/Rails/Djangoرفتار هر ORM
خواندن SQL، تنظیمات، پیام‌های خطاسازوکار
راه‌حل کامل: N+1، import، پیمایش، گزارش، تستحل مسئله‌های کلاسیک
کدام ابزار برای کدام عملیاتانتخاب ابزار
مونولیت، میکروسرویس، replica و مقیاسدر معماری
بازتولید N+1 و جاافتادن ردیف در chunkآزمایشگاه
باورهای غلط، یادسپار و واژه‌هابدفهمی‌ها، یادسپار، واژه‌نامه

همه‌چیز در یک دقیقه ​

دام‌ها. هر ردیف در بخش دام‌ها باز می‌شود.

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

loaderها. هر روش خواندن رابطه یا ردیف چه هزینه‌ای دارد.

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

نویسنده‌های bulk. هر کدام چه چیزی را رد می‌کند.

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

چرا دام‌های ORM وجود دارند ​

دیتابیس رابطه‌ای مجموعه‌هایی از ردیف را نگه می‌دارد و به پرسش‌های مجموعه‌ای جواب می‌دهد. اپلیکیشن گراف‌هایی از شیء نگه می‌دارد و هر بار یک ارجاع را دنبال می‌کند. ORM بین این دو ترجمه می‌کند و هزینه و غافلگیری در همین ترجمه پنهان است. مصالحه همیشه یکی است:

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

تصویری از زندگی روزمره. یک انبار. اگر برای هر جعبه یک پیک بفرستید، ۳۰۰ جعبه یعنی ۳۰۰ سفر. اگر یک لیست برداشت (pick list) بدهید، انبار یک پالت بار می‌کند و یک بار برمی‌گردد. lazy loading پیکی است که هر بار نام جعبهٔ بعدی را بگویید دوباره می‌آید؛ eager loading همان لیست برداشت است؛ bulk insert همان پالت. مدیر انبار (دیتابیس) با هر دو راحت است، اما زمان تحویل شما (latency) نه.

سه بدفهمی رایج، از همان ابتدا ​

  1. «$book->author خواندن یک property است، پس رایگان است.» شبیه دسترسی به حافظه است، اما بار اول یک round trip شبکه‌ای است.
  2. «ORM کند است.» معمولاً ORM وفادار است: دقیقاً همان statement هایی را فرستاده که کد شما خواسته، یکی در هر دور حلقه. هزینه در الگوی دسترسی است، نه در کتابخانه.
  3. «متدهای bulk فقط save() سریع‌ترند.» عملیات متفاوتی‌اند: هیچ model ای بارگذاری نمی‌شود، پس event، cast، mutator، observer و timestamp خودکار اجرا نمی‌شود.

ناهمخوانی شیء-رابطه‌ای (Impedance Mismatch) تکمیلی ​

به زبان ساده: شیءها به هم اشاره می‌کنند و مجموعه نگه می‌دارند؛ جدول‌ها ردیف‌های تخت دارند و با کلید به هم مربوط می‌شوند. تبدیل این دو به هم یک مسئلهٔ ترجمه است، نه کپی.

سوءبرداشت رایج: «ORM ناهمخوانی را از بین می‌برد.» فقط مدیریتش می‌کند؛ تفاوت‌ها می‌مانند و به شکل N+1، مشکل identity، رفتار null و اصطکاک migration بیرون می‌زنند.

تعریف: مجموعهٔ تفاوت‌های مفهومی بین گراف شیء در حافظه و schema رابطه‌ای: هویت (ارجاع شیء در برابر primary key)، رابطه‌ها (اشاره‌گر و مجموعه در برابر کلید خارجی و join)، وراثت (سلسله‌مراتب کلاس در برابر جدول)، دانه‌بندی (یک شیء غنی در برابر چند ردیف)، پیمایش (دنبال کردن اشاره‌گر در برابر JOIN) و نوع داده (نوع زبان در برابر نوع ستون، NULL، time zone). Martin Fowler در 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." و اضافه می‌کند که به حق باید «مسئلهٔ نگاشت in-memory/relational» نامیده شود.

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

واژگان از کجا آمده‌اند ​

بیشتر واژه‌های این حوزه (Active Record، Data Mapper، Identity Map، Unit of Work، Lazy Load، Repository) از فهرست الگوهای Martin Fowler برای اپلیکیشن‌های سازمانی می‌آیند. تعریف‌های یک‌خطی زیر عین عبارت فهرست خود اوست:

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

خود اصطلاح «N+1» را به منبع اولیه‌اش ردیابی نکرده‌ام؛ مستندات Laravel آن را نام می‌برد و می‌شمارد و من همان واژه را به کار می‌برم. دربارهٔ «impedance mismatch» هم به توصیف Fowler از مسئله ارجاع می‌دهم، نه به یک ابداع. مستندات Laravel 13.x هزینه را برای فهرست ۲۵ کتاب می‌شمارد: "one query for the original book, and 25 additional queries to retrieve the author of each book" و نشان می‌دهد یک with('author') یعنی "only two queries will be executed". GORM همان راه‌حل را مستند کرده است: "GORM allows eager loading relations in other SQL with Preload" و "Preload loads the association data in a separate query, Join Preload will loads association data using left join". کتابخانه‌های Go lazy loading ندارند که خاموش شود؛ پس N+1 در Go همیشه query ای است که خودتان داخل حلقه نوشته‌اید.

دام‌ها، یکی‌یکی ​

همهٔ مثال‌ها از این schema استفاده می‌کنند که آزمایشگاه می‌سازد: 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). فایل‌های snippet با نام Models.php، Lab.php، Bulk.php و Migration.php سمت Laravel را دارند؛ سمت Go در پکیج‌های before، after، gorm، pgx و chunk است.

N+1 و lazy loading حیاتی ​

به زبان ساده: یک فهرست می‌خواهید، بعد برای هر آیتم فهرست یک سؤال دیگر از دیتابیس می‌پرسید. برای ۲۵ آیتم می‌شود ۲۶ سؤال به جای ۲.

سوءبرداشت رایج: «N+1 فقط با هزاران ردیف مهم است.» هر query اضافه یک round trip شبکه، یک parse و یک جستجوی plan هزینه دارد؛ ۲۵ ردیف با ۲ میلی‌ثانیه برای هر سفر همین حالا ۵۰ میلی‌ثانیه اضافه می‌کند و با ۲۰۰ ردیف در صفحه و دیتابیس شلوغ به اصلی‌ترین latency تبدیل می‌شود. و این باور که «دیتابیس سریع است پس مهم نیست»: دیتابیس بیکار است و اپلیکیشن شما منتظر سفر بعدی.

تعریف: الگوی دسترسی ای که در آن کد یک query برای N ردیف والد می‌زند و بعد به ازای هر والد یک query برای ردیف یا مجموعهٔ مرتبط، یعنی 1 + N statement. بارگذاری تنبل (lazy loading) سازوکار آن است: رابطه در اولین خواندن property بارگذاری می‌شود.

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

سناریوهای واقعی: فهرست ادمین که نام مشتری هر سفارش را چاپ می‌کند (1 + 50)؛ قالب Blade که $author->books->count() را صدا می‌زند (پنهان در view)؛ resource ای در API که author و publisher را شامل می‌شود (1 + 2N)؛ resolver هر فیلد در GraphQL (N+1 کلاسیکی که DataLoader دسته‌بندی‌اش می‌کند)؛ handler ای در Go که GetAuthor(ctx, id) را در حلقه صدا می‌زند؛ serializer ای که رابطه‌ای را می‌خواند که controller هرگز بارگذاری نکرده.

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

راه‌حل.

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

Go: تابع LoadBooksByAuthor یک WHERE author_id = ANY(...) می‌فرستد؛ کد در پکیج after است.

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

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

type Book struct {
	AuthorID int64
	Title    string
}

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

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

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

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

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

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

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

پکیج «before» همان کار را غلط انجام می‌دهد: برای هر نویسنده یک query، دستی نوشته شده.

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

import (
	"context"
	"database/sql"
)

type Book struct {
	AuthorID int64
	Title    string
}

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

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

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

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

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

نسخهٔ «before» در Eloquent همان N+1 به‌علاوهٔ عادت‌هایی است که پشت آن می‌آیند:

php
<?php

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

namespace App\Http\Controllers;

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

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

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

        return $rows;
    }
}

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

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

Laravel: with query دوم را اجرا می‌کند و withCount عدد را داخل SQL حساب می‌کند.

php
<?php

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

namespace App\Http\Controllers;

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

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

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

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

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

Eager loading: with، load، loadMissing، withCount، withSum حیاتی ​

به زبان ساده: از قبل به ORM بگویید چه داده‌های مرتبطی لازم دارید تا همه را در تعداد ثابتی query بیاورد.

سوءبرداشت رایج: «eager loading همیشه سریع‌تر است.» round trip را با حافظه و هزینهٔ ساخت و تطبیق نتیجه معاوضه می‌کند. eager load کردن یک میلیون والد با همهٔ رابطه‌ها می‌تواند از N+1 ای که جایش آمده کندتر باشد. و: «with یک JOIN می‌سازد.» در Eloquent نمی‌سازد؛ یک query دوم با WHERE fk IN (...) می‌زند و نتیجه را در PHP به هم وصل می‌کند.

تعریف: بارگذاری پیشاپیش (eager loading) یعنی بارگذاری model های مرتبط از قبل، با یک query برای هر رابطه، به جای بارگذاری در اولین خواندن property.

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

مستندات Laravel می‌گوید وقتی ستون‌های یک رابطه را محدود می‌کنید باید ستون‌های id و کلید خارجی را نگه دارید، وگرنه وصل کردن فرزندها به والدها شکست می‌خورد. همان صفحه withSum، withMin، withMax، withAvg و withExists را هم‌خانوادهٔ withCount مستند می‌کند و می‌گوید نتیجه در attribute ای به شکل {relation}_{function}_{column} می‌نشیند.

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

Nested eager loading با نقطه نوشته می‌شود: Author::with('books.comments.user') به ازای هر سطح یک query اضافه می‌زند و with('books.comments:id,commentable_id,body') برگ را باریک می‌کند. عمق، تعداد ردیف را ضرب می‌کند: 100 نویسنده × 20 کتاب × 30 نظر یعنی 60,000 model نظر در حافظه. Model::automaticallyEagerLoadRelationships() (مستندات Laravel، «Automatic Eager Loading») رابطه را وقتی یکی از model های همان مجموعه آن را می‌خواند برای همه بارگذاری می‌کند و حلقهٔ تودرتوی بالا را بدون نوشتن with به یک query در هر سطح می‌رساند؛ باز هم همهٔ ستون‌ها را می‌آورد.

GORM:

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

سه شکل Go ORM کنار هم در snippet ای به نام gorm است که با یک callback تعداد query ها را می‌شمارد و SQL را با ToSQL چاپ می‌کند:

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

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

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

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

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

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

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

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

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

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

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

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

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

سناریوهای واقعی: داشبورد مشتری‌ها با تعداد سفارش (withCount)؛ فهرست فاکتور با آیتم‌ها و مالیات (with تودرتو)؛ فید با نویسنده و آخرین نظر (with با قید به‌علاوهٔ Joins)؛ خروجی export که فقط id و email می‌خواهد.

Preload یا join؟

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

سخت‌گیری: preventLazyLoading و shouldBeStrict مهم ​

به زبان ساده: برنامه را در توسعه بلند و واضح خراب کنید وقتی lazy loading می‌کند، تا یک with() فراموش‌شده به جای صفحهٔ کند، یک تست قرمز باشد.

سوءبرداشت رایج: «روشن کردنش در production برنامه را امن‌تر می‌کند.» صفحه‌هایی را که امروز کار می‌کنند به exception تبدیل می‌کند. بیرون از production روشنش کنید، یا در production فقط log کنید.

تعریف: Model::preventLazyLoading() باعث می‌شود lazy loading خطای Illuminate\Database\LazyLoadingViolationException بدهد. Model::handleLazyLoadingViolationUsing(fn) به جای throw، handler شما را صدا می‌زند. Model::shouldBeStrict() سه بررسی را با هم روشن می‌کند: preventLazyLoading، preventSilentlyDiscardingAttributes و preventAccessingMissingAttributes (از سورس Model.php در 13.x خوانده‌ام؛ صفحهٔ مستندات اولی و دومی را جدا توصیف می‌کند و از shouldBeStrict اسمی نمی‌برد).

php
<?php

namespace App\Providers;

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

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

در Go چیزی برای جلوگیری وجود ندارد؛ معادلش شمارندهٔ query در تست‌هاست (بخش تست) و مرور کد: هر فراخوانی query داخل for.

انتخاب ستون و هزینهٔ hydration مهم ​

به زبان ساده: هر ردیفی که بارگذاری می‌کنید به شیئی با همهٔ ستون‌ها، cast ها و رابطه‌هایش تبدیل می‌شود. صفحه‌ای که فقط یک نام لازم دارد هزینهٔ کل ردیف را می‌دهد.

سوءبرداشت رایج: «هزینه همان SQL است.» در جدول‌های عریض هزینه اغلب در PHP یا Go است: خواندن بایت‌ها، ساخت شیء‌ها، اجرای cast و mutator، و حافظه‌ای که اشغال می‌کنند.

تعریف: hydration یعنی تبدیل ردیف‌های نتیجه به model (تخصیص حافظه، مقداردهی attribute ها، اعمال cast، نگه داشتن مقدار اصلی برای dirty checking). هزینه با ردیف × ستون × قابلیت‌ها (cast، accessor، observer) رشد می‌کند.

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

سناریوهای واقعی: export CSV ای که User::all() را بارگذاری می‌کند و حافظه تمام می‌شود (Allowed memory size of 134217728 bytes exhausted)؛ APIای که فقط id و name برمی‌گرداند ولی 40 ستون از جمله یک blob از نوع jsonb را select می‌کند؛ صفحهٔ فهرستی که ستون TEXT حاوی HTML رندرشده را بارگذاری می‌کند. انتخاب ستون همچنین به PostgreSQL اجازه می‌دهد از index-only scan استفاده کند (بخش Indexing) و مقدارهای TOAST را نخواند.

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

پیمایش جدول بزرگ: chunk، chunkById، lazy، cursor حیاتی ​

به زبان ساده: وقتی جدول برای یک‌جا بارگذاری بزرگ است آن را برش‌برش می‌خوانید. اینکه برش بعدی را چطور انتخاب کنید تعیین می‌کند ردیفی را از دست می‌دهید یا نه.

سوءبرداشت رایج: «chunk پیش‌فرض امن برای به‌روزرسانی دسته‌ای است.» فقط وقتی امن است که حلقه ردیف‌های منطبق با filter را عوض نکند. مستندات خود Laravel هشدار می‌دهد که استفاده از chunk روی ستونی که همزمان به‌روز می‌کنید "could lead to unexpected and inconsistent results".

تعریف: chunk(n, fn) برای k = 0, n, 2n, ... اجرا می‌کند ORDER BY id LIMIT n OFFSET k؛ chunkById(n, fn) اجرا می‌کند WHERE id > last ORDER BY id LIMIT n؛ lazy(n) همان chunk است که در یک LazyCollection تخت شده؛ lazyById(n) همان chunkById تخت‌شده؛ و cursor() یک query می‌زند و با generator در PHP هر بار یک model می‌دهد. (در سورس 13.x، chunk با forPage یعنی offset/limit صفحه‌بندی می‌کند.)

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

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

سناریوهای واقعی: تغییر in_stock = false برای کاتالوگ یک تأمین‌کننده (مثال بالا)؛ ایندکس دوبارهٔ سند‌ها در موتور جست‌وجو؛ ارسال اعلان به هر کاربری که فاکتور باز دارد؛ حذف ردیف‌های soft-delete شدهٔ قدیمی‌تر از یک سال.

معادل Go هر دو شکل را نشان می‌دهد و آزمایش دوم آزمایشگاه است:

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

import (
	"context"
	"database/sql"
)

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

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

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

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

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

برای مدل هزینهٔ offset در برابر keyset به Pagination: Offset vs Keyset نگاه کنید. دربارهٔ cursor() و بافر شدن ردیف‌ها در PDO به Cursors & Streaming: در PostgreSQL نتیجهٔ pdo_pgsql به‌طور پیش‌فرض کامل fetch می‌شود، پس cursor() حافظهٔ شیء‌های model را کم می‌کند نه حافظهٔ driver را.

نوشتن bulk: insert، upsert، insertOrIgnore، mass update حیاتی ​

به زبان ساده: به جای statement های زیاد، ردیف‌های زیاد را در یک statement بفرستید. بسیار سریع‌تر است و رفتار هر ردیف را که شاید به آن تکیه داشتید رد می‌کند.

سوءبرداشت رایج: «upsert یک save() بهتر است.» مستقیم SQL می‌نویسد: هیچ model ای بارگذاری نمی‌شود، پس event، observer، cast و mutator اجرا نمی‌شوند و روی ستون‌های conflict یک unique index لازم دارد.

تعریف: نوشتن bulk یعنی یک statement که روی ردیف‌های زیاد اثر می‌گذارد (INSERT ... VALUES (...), (...)، INSERT ... ON CONFLICT، UPDATE ... WHERE، COPY). mass update یعنی یک UPDATE از راه query builder؛ per-row save هر model را بارگذاری می‌کند، تغییر می‌دهد و می‌نویسد.

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

insertOrIgnore احتیاط می‌خواهد. مستندات Laravel می‌گوید "will ignore errors while inserting records"، خطای کلید تکراری نادیده گرفته می‌شود و "other types of errors may also be ignored depending on the database engine"، و strict mode در MySQL را دور می‌زند. در PostgreSQL به ON CONFLICT DO NOTHING تبدیل می‌شود که فقط تعارض unique را نادیده می‌گیرد. مستندات Laravel upsert را "a single, atomic operation" توصیف می‌کند؛ همهٔ دیتابیس‌ها به‌جز SQL Server روی ستون‌های conflict به primary یا unique index نیاز دارند و MySQL و MariaDB آرگومان را نادیده می‌گیرند و از کلیدهای خودشان استفاده می‌کنند.

سقف پارامتر. پروتکل PostgreSQL در یک statement حداکثر 65,535 bind parameter حمل می‌کند (شمارندهٔ 16 بیتی)، prepared statement در MySQL هم سقف 65,535 placeholder دارد (خطای 1390: "Prepared statement contains too many placeholders") و SQLITE_MAX_VARIABLE_NUMBER در SQLite از نسخهٔ 3.32 پیش‌فرض 32,766 است. insert چندردیفی ردیف × ستون پارامتر مصرف می‌کند، پس batch کنید: 1,000 ردیف سه‌ستونه یعنی 3,000 پارامتر. unnest با آرایه (snippet ای به نام pgx) تعداد پارامتر را برابر تعداد ستون‌ها نگه می‌دارد.

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

import (
	"context"
	"fmt"
	"os"

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

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

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

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

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

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

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

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

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

namespace App\Services;

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

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

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

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

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

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

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

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

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

        return $book;
    }
}

mass update در برابر per-row save:

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

مستندات Laravel می‌گوید: "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." همین برای mass delete و insert و upsert و insertOrIgnore هم صادق است. اگر یک observer، cache را باطل می‌کند، ردیف audit می‌نویسد یا index جست‌وجو را به‌روز می‌کند، مسیر bulk از آن می‌گذرد: کار را خودتان dispatch کنید، یا وقتی رفتار مهم‌تر از سرعت است از راه model و در chunk (chunkById به‌علاوهٔ save) بنویسید. saveQuietly() و Model::withoutEvents(fn) برعکس‌اند: مسیر model را اجرا می‌کنند ولی eventها را بی‌صدا می‌کنند.

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

transaction ضمنی و مرز transaction حیاتی ​

به زبان ساده: هر statement در یک transaction اجرا می‌شود. اگر خودتان باز نکرده باشید، دیتابیس برای هر statement یکی باز و commit می‌کند؛ حلقهٔ 300 تا save() یعنی 300 commit جدا.

سوءبرداشت رایج: «متد سرویس من یک واحد کار است، پس یک transaction است.» بدون DB::transaction یا db.BeginTx به تعداد statement ها transaction است و crash در میانه نیمی از کار را commit شده می‌گذارد.

تعریف: مرز تراکنش (transaction) جفت BEGIN و COMMIT دور statement هایی است که باید با هم موفق شوند. ORM هم ممکن است مرز خودش را بیفزاید: GORM هر create و update و delete را به‌طور پیش‌فرض داخل transaction می‌برد. مستنداتش می‌گوید "write (create/update/delete) operations run inside a transaction to ensure data consistency" و با SkipDefaultTransaction: true می‌توانید خاموشش کنید برای "about 30%+ performance improvement". Laravel چنین نمی‌کند: save() بیرون از DB::transaction یک statement با autocommit است. فقط فراخوانی‌ای که مستنداتش بگوید خودش را می‌پیچد، مثل deleteOrFail که مستندات می‌گوید در exception rollback می‌کند.

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

سه پیامد برای طراحی. اتمیک بودن یک batch مرز صریح می‌خواهد؛ مبانی ACID در ACID & Transactions است. طول transaction: transaction ای دور حلقه‌ای که API HTTP هم صدا می‌زند قفل و connection را در تمام آن مدت نگه می‌دارد (بخش Connection Pooling)؛ مرز را فقط دور کار دیتابیس بگذارید. side effect ها (ایمیل، queue) باید بعد از commit اجرا شوند: در Laravel با DB::afterCommit، job صف با afterCommit یا ShouldDispatchAfterCommit روی eventها؛ در Go بعد از برگشتن tx.Commit(). فراخوانی‌های تودرتوی DB::transaction از savepoint استفاده می‌کنند؛ attempts بن‌بست یا خطای serialization را دوباره تلاش می‌کند، بخش Deadlocks.

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

نبود Identity Map در Eloquent مهم ​

به زبان ساده: از Eloquent دوبار همان ردیف را بخواهید، دو شیء متفاوت (نبود Identity Map) می‌گیرید. یکی را تغییر دهید، دیگری خبردار نمی‌شود.

سوءبرداشت رایج: «find(1) هر بار همان شیء را برمی‌گرداند، مثل cache جلسه.» این قابلیت Data Mapper است (Doctrine، Hibernate). Eloquent، GORM و Rails برای هر query نمونهٔ تازه می‌سازند.

تعریف: identity map هر entity بارگذاری‌شده را در هر unit of work فقط یک بار، با کلید primary key نگه می‌دارد تا بارگذاری دوم همان نمونه را برگرداند. Fowler: "Ensures that each object gets loaded only once by keeping every loaded object in a map."

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

سناریوهای واقعی: دو سرویس در یک request هر کدام کاربر را بارگذاری می‌کنند و فیلد متفاوتی را ویرایش می‌کنند و save() دوم اولی را بازنویسی می‌کند (با dirty tracking پیش‌فرض فقط attribute های تغییرکرده نوشته می‌شوند و معمولاً امن است؛ ذخیرهٔ کل ردیف مثل Save در GORM این‌طور نیست)؛ تستی که دو نمونه را با === مقایسه می‌کند و می‌افتد؛ کدی که برای «داده تازه» model را داخل حلقه دوباره بارگذاری می‌کند و query ها را دوبرابر می‌کند. راه‌حل‌ها: به جای id خود شیء را پایین بدهید؛ وقتی وضعیت فعلی دیتابیس را می‌خواهید $book->refresh() بزنید؛ برای نمونهٔ تازه fresh()؛ یا وقتی دامنه غنی است به ORM از نوع Data Mapper بروید.

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

دام‌های caching مهم ​

به زبان ساده: cache جلوی ORM خواندن را سریع می‌کند و ارائهٔ شیء کهنه یا غلط را آسان.

سوءبرداشت رایج: «Cache::remember روی یک model رایگان است.» یک عکس لحظه‌ای را serialize می‌کند: نوشتن‌های بعدی آن را عوض نمی‌کند، شیء cache شده lazy load ها را پنهان می‌کند (بعد از unserialize ممکن است رابطه نباشد) و cache hit از event ها و scope هایی که فکر می‌کردید اعمال می‌شوند رد می‌شود.

تعریف: جاهایی که cache کنار ORM خراب می‌شود: cache کردن model های hydrate شده به جای آرایه، باطل‌سازی نشدن بعد از نوشتن bulk (که event نمی‌فرستد، پس باطل‌سازی مبتنی بر event اجرا نمی‌شود)، cache stampede روی کلید داغ، cache کردن نتیجهٔ هر کاربر زیر کلید سراسری، و race مرحلهٔ بررسی-سپس-نوشتن در read-through cache. query cache داخل یک request (cache هر request در Rails، second-level cache در Hibernate) چیز دیگری است و در Eloquent به‌طور پیش‌فرض نیست.

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

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

Query builder در برابر raw SQL و SQL injection حیاتی ​

به زبان ساده: ORM فقط از مقدارهایی که خودش bind می‌کند محافظت می‌کند. هر چه خودتان به رشته بچسبانید، محافظتش با شماست.

سوءبرداشت رایج: «ORM دارم، پس SQL injection ندارم.» where('name', $x) مقدار $x را bind می‌کند؛ whereRaw("name = '$x'")، orderBy($request->sort)، DB::unprepared($sql) و selectRaw با مقدار درون‌یابی‌شده نه. مستندات Laravel می‌گوید query builder "uses PDO parameter binding to protect your application against SQL injection attacks"، "PDO does not support binding column names" و "Laravel cannot guarantee that any query using raw expressions is protected against SQL injection vulnerabilities".

تعریف: مقدار وقتی امن است که به‌صورت پارامتر bind شده (?، $1، :name) برسد و متن SQL ثابت باشد. شناسه‌ها (نام ستون و جدول، جهت ORDER BY، در بعضی driverها LIMIT) bind نمی‌شوند و باید از یک whitelist بیایند.

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

جایی که raw SQL ابزار درست است: گزارش با window function، CTE بازگشتی، FOR UPDATE SKIP LOCKED، COPY، join تنظیم‌شده با دست. برای filter های پویا از query builder (ترکیب‌پذیر است)، برای رفتار یک entity از model و برای query های ثابت تحلیلی از raw SQL (یا sqlc) استفاده کنید. بحث injection در عمق، با prepared statement و نقش‌ها، در Database Security است.

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

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

SQL بد تولیدشده توسط ORM: زنجیرهٔ OR، IN بزرگ، subquery همبسته مهم ​

به زبان ساده: ORM همان SQL ای را می‌نویسد که شما توصیف کردید، نه آنچه planner دوست دارد. بعضی PHP یا Go کاملاً طبیعی statement کند یا شکننده تولید می‌کند.

سوءبرداشت رایج: «اگر کد تمیز است SQL هم خوب است.» شکل‌های زیر در کد تمیزند و در SQL گران.

تعریف: شکل‌هایی از query (مثل OR chain، یعنی زنجیرهٔ طولانی OR) که ORM ها آسان تولید می‌کنند و دیتابیس‌ها بد از پسشان برمی‌آیند.

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

SQL تولیدشده خواندنی است. در Eloquent: ->toRawSql(). مستندات Laravel برای همین هدف dumpRawSql و ddRawSql را دارد. پیش از پذیرفتن کد، statement را بخوانید و EXPLAIN (ANALYZE, BUFFERS) اجرا کنید؛ بخش سازوکار و Query Planning.

Pagination تکمیلی ​

به زبان ساده: paginate() راحت است و هر صفحه یک COUNT(*) به‌علاوهٔ پویش OFFSET هزینه دارد.

سوءبرداشت رایج: «pagination یک قابلیت UI است.» انتخاب شکل query با منحنی هزینه است؛ صفحهٔ 5,000 صد هزار ردیف را می‌خواند و دور می‌ریزد.

تعریف: Laravel سه ابزار دارد: paginate (شمارهٔ صفحه، count می‌زند)، simplePaginate (قبلی/بعدی، بدون count) و cursorPaginate (keyset). GORM و sqlc صفحه‌بندی نمی‌کنند: LIMIT/OFFSET یا شرط keyset را خودتان می‌نویسید. مدل کامل هزینه، مقایسهٔ row-value و cursor مات در Pagination: Offset vs Keyset است؛ این صفحه فقط هشدار می‌دهد که chunk همان offset paging با callback است.

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

Soft delete و index مهم ​

به زبان ساده: حذف نرم (soft delete) به جای حذف ردیف، آن را «حذف‌شده» علامت می‌زند. ردیف هنوز جا می‌گیرد، هنوز در هر index هست و هنوز مقدارهای unique را اشغال می‌کند.

سوءبرداشت رایج: «soft delete یک DELETE امن است.» هر query را عوض می‌کند (یک WHERE deleted_at IS NULL پنهان)، کلید خارجی‌ها را زنده نگه می‌دارد، constraint یکتایی را می‌شکند و نیاز پاک‌سازی داده را برآورده نمی‌کند.

تعریف: SoftDeletes در Eloquent ستون deleted_at را پر می‌کند و یک global scope می‌افزاید؛ GORM برای model هایی با فیلد gorm.DeletedAt همین کار را می‌کند ("If your model includes a gorm.DeletedAt field (which is included in gorm.Model), it will get soft delete ability automatically!") و رکوردهای soft-delete شده هنگام query نادیده گرفته می‌شوند.

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

رابطه‌های polymorphic و از دست رفتن کلید خارجی مهم ​

به زبان ساده: یک ستون (commentable_id) id ای دارد که می‌تواند به جدول‌های مختلف تعلق داشته باشد و ستون دیگر (commentable_type) می‌گوید کدام. دیتابیس نمی‌تواند وجود id را بررسی کند.

سوءبرداشت رایج: «رابطهٔ polymorphic یک کلید خارجی معمولی با نوع است.» کلید خارجی به یک جدول اشاره می‌کند؛ این یکی به چند جدول، پس constraint ممکن نیست و ردیف یتیم پیدا می‌شود.

تعریف: ستون‌های morphTo، morphMany و morphs() در Eloquent؛ polymorphic: true در Rails؛ در Doctrine با وراثت نگاشت می‌شود.

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

جایگزین‌هایی که یکپارچگی را نگه می‌دارند: یک جدول برای هر والد (book_comments، author_comments)، یک ستون nullable برای هر والد با CHECK (num_nonnulls(book_id, author_id) = 1)، یا یک جدول supertype به نام commentables که هر دو والد به آن ارجاع می‌دهند. مصالحه‌ها در Schema Design آمده است.

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

Timestamp و time zone مهم ​

به زبان ساده: created_at همان چیزی است که ساعت اپلیکیشن گفت، در هر zone ای که اپلیکیشن و دیتابیس روی آن توافق دارند، و ممکن است یکی نباشند.

سوءبرداشت رایج: «timestamp یک لحظه را نگه می‌دارد.» در PostgreSQL نوع timestamp یک ساعت دیواری بدون zone است؛ timestamptz یک لحظه است (داخلاً UTC). DATETIME در MySQL zone ندارد؛ TIMESTAMP به UTC تبدیل می‌کند و سقفش سال 2038 است.

تعریف: Eloquent در save()، touch()، create() و upsert (فقط در به‌روزرسانی) مقدار created_at/updated_at را با now() در time zone اپلیکیشن (config('app.timezone')، پیش‌فرض UTC) می‌گذارد؛ insert bulk و mass update آن‌ها را دست نمی‌زنند. GORM با autoCreateTime/autoUpdateTime و NowFunc مقدار CreatedAt/UpdatedAt را می‌گذارد.

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

Optimistic locking در ORM ها مهم ​

به زبان ساده: در قفل خوش‌بینانه (optimistic locking) به ردیف یک شمارهٔ نسخه اضافه کنید؛ به‌روزرسانی فقط وقتی موفق می‌شود که نسخه هنوز همان باشد که خوانده‌اید.

سوءبرداشت رایج: «ORM جلوی بازنویسی همزمان را می‌گیرد.» Eloquent و GORM نمی‌گیرند مگر خودتان ستون version بیفزایید؛ save() attribute های تغییرکرده را می‌نویسد و آخرین نویسنده برنده می‌شود. سازوکار، حلقهٔ retry و زمان ترجیح FOR UPDATE در Optimistic vs Pessimistic Locking است.

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

migration های تولیدشده توسط ORM حیاتی ​

به زبان ساده: ابزارهایی که model ها را با دیتابیس مقایسه می‌کنند و migration می‌نویسند نمی‌دانند جدول شما 800 گیگابایت است.

سوءبرداشت رایج: «migration خودکار امن است چون مکانیکی است.» مکانیکی است، نه آگاه از production: rename را با drop و add انجام می‌دهد، NOT NULL با default را روی موتورهای قدیمی‌تر کل جدول را بازنویسی می‌کند، index را بدون CONCURRENTLY می‌سازد و قفل ACCESS EXCLUSIVE می‌گیرد.

تعریف: ابزارهای diff روی schema (migrations:diff در Doctrine، makemigrations در Django، --autogenerate در Alembic، Atlas، AutoMigrate در GORM، Schema.Create در Ent، schema dump در Rails) schema مطلوب و واقعی را مقایسه می‌کنند و DDL تولید می‌کنند.

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

عادت Laravel: php artisan migrate --pretend SQL را چاپ می‌کند؛ بخوانیدش. AutoMigrate در GORM هرگز ستون‌های بلااستفاده را حذف نمی‌کند و این drift را پنهان می‌کند. جزئیات expand/contract، سطح قفل و backfill در Zero-Downtime Schema Migrations است.

رفتار هر ORM ​

Active Record در برابر Data Mapper و بحث repository مهم ​

به زبان ساده: در Active Record خود شیء model می‌داند چطور ذخیره شود. در Data Mapper شیء ساده است و شیء دیگری ذخیره‌اش می‌کند.

سوءبرداشت رایج: «Data Mapper تمیزتر است، پس بهتر است.» کد و مفهوم بیشتری می‌خواهد (unit of work، identity map، ترتیب flush، entity جداشده). برای اپلیکیشن‌های CRUD محور، Active Record سریع‌تر ساخته می‌شود؛ Data Mapper وقتی می‌ارزد که مدل دامنه غنی است و نباید از دیتابیس خبر داشته باشد.

تعریف: عبارت Fowler در جدول واژگان است. Active Record: Eloquent، ActiveRecord در Rails، ORM در Django. Data Mapper: Doctrine ORM، Hibernate، SQLAlchemy ORM، Entity Framework، Ent (builder تولیدشده، struct ساده). هیچ‌کدام همان query builder نیست که فقط SQL می‌سازد.

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

بحث repository همان پرسش یک سطح بالاتر است. تعریف Fowler می‌گوید repository "mediates between the domain and data mapping layers using a collection-like interface". دلیل موافق: یک جا برای کد query، درزی برای تست، و رابط پایدار وقتی ORM عوض می‌شود. دلیل مخالف، که در جامعهٔ Laravel رایج است: با Eloquent، repository ای که Model::find را می‌پیچد لایه‌ای است بی‌انتزاع تازه، نوع‌های Eloquent را از طریق مقدار برگشتی لو می‌دهد و بدون اینکه برای هر use case یک متد اضافه شود نمی‌تواند انتخاب‌های with() را بیان کند. میانهٔ عملی: برای هر use case یک repository (یا query object) که داده‌های ساده برمی‌گرداند و eager loading را داخل خودش اعلام می‌کند، تا view نتواند N+1 بسازد.

هر ORM و کتابخانه واقعاً چه می‌کند ​

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

GORM، sqlx، pgx، sqlc، Ent و Bun در Go، در عمل:

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

مستندات sqlc ابزار را در یک خط توصیف می‌کند: "sqlc generates fully type-safe idiomatic Go code from SQL." توصیف GORM از Preload و Joins همان است که بالا آمد. قابلیت‌هایی که برای Ent، Bun، Doctrine، Hibernate، SQLAlchemy، Rails و Django می‌آورم از مستنداتشان است (صفحه‌های Ent و Bun و Doctrine ذخیره شده؛ بقیه از حافظه از مستندات عمومی است، پس نام دقیق متدها را در نسخهٔ خودتان بررسی کنید).

سازوکار (Mechanics) ​

خواندن SQL ای که ORM می‌فرستد حیاتی ​

چیزی را که نمی‌بینید نمی‌توانید درست کنید. هر ORM راهی برای چاپ SQL دارد؛ پیش و پس از هر تغییر کارایی از آن استفاده کنید.

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

نشانهٔ N+1 در pg_stat_statements یک statement نرمال‌شده (... WHERE author_id = $1) با calls بسیار زیاد و mean_exec_time ناچیز است، کنار statement والد که بسیار کمتر صدا زده شده.

تنظیمات (Knobs) مهم ​

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

پیام‌های خطایی که می‌بینید حیاتی ​

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

حل مسئله‌های کلاسیک ​

N+1 در endpoint فهرست ​

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

کد: بخش N+1 و eager loading.

import فایل با 1,000,000 ردیف ​

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

پیمایشی که همان چیزی را به‌روز می‌کند که می‌خواند ​

در Laravel از chunkById یا lazyById، در Go از FindInBatches یا حلقهٔ keyset دستی (پکیج chunk)، یا وقتی منطق تک‌ردیفی لازم نیست از یک UPDATE ... WHERE مجموعه‌ای استفاده کنید. برای جدولی با صدها میلیون ردیف هر batch را محدود کنید و بین آن‌ها commit کنید تا قفل طولانی و bloat نداشته باشید؛ بخش Working with Billion-Row Tables.

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

query های گزارش ​

گزارشی که پنج جدول را join می‌کند و یک میلیون ردیف را aggregate می‌کند مسئلهٔ SQL است. آن را به صورت SQL بنویسید (selectRaw/groupBy در query builder، DB::select یا sqlc)، plan را بخوانید و ردیف‌های ساده برگردانید. اگر سنگین است روی replica یا در materialized view اجرا کنید؛ بخش OLTP vs OLAP و Replication.

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

تست: دیتابیس واقعی یا mock ​

به زبان ساده: ORM ای که mock شده فقط ثابت می‌کند کد شما mock را صدا می‌زند. فقط دیتابیس واقعی SQL را ثابت می‌کند.

سوءبرداشت رایج: «mock کردن repository تست‌ها را سریع و به همان اندازه خوب می‌کند.» mock نمی‌تواند N+1، join غلط، نقض unique، رفتار NULL، collation یا migration را بگیرد.

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

قاعده‌هایی که جواب می‌دهند: migration ها را روی همان موتوری اجرا کنید که deploy می‌کنید؛ یک seed کوچک واقع‌گرایانه نگه دارید؛ برای endpoint های فهرست تعداد query را assert کنید؛ shouldBeStrict را در bootstrap تست روشن کنید؛ پاک‌سازی transaction-per-test را ترجیح دهید؛ و قابلیت‌های همزمانی را روی سرور واقعی تست کنید (بخش آزمایشگاه isolation).

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

انتخاب ابزار ​

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

در معماری: از یک پردازه تا سیستم توزیع‌شده ​

مونولیت (Monolith): یک پردازه، یک دیتابیس ​

یک مونولیت Eloquent با strict mode روشن در CI ساده‌ترین تنظیم درست است. هر endpoint فهرست with اش را اعلام می‌کند؛ یک feature test تعداد query را assert می‌کند؛ chunkById کارهای دسته‌ای را انجام می‌دهد؛ DB::transaction دور هر use case است. مثال: فروشگاهی با orders، order_items و customers. فهرست سفارش‌ها Order::with('customer:id,name')->withCount('items')->cursorPaginate(25) را بارگذاری می‌کند: دو query در هر صفحه، حافظهٔ ثابت و بدون lazy loading.

مونولیت ماژولار و چند دیتابیس ​

وقتی ماژول‌ها مالک جدول‌های خودشان هستند، رابطه‌ای که از ماژول عبور کند نقض مرز است. رابطه‌های Eloquent بین ماژول‌ها (مثلاً Order با belongsTo(Customer::class) از ماژول دیگر) schema ها را به هم گره می‌زنند و اگر جدول‌ها در دیتابیس‌های جدا باشند with غیرممکن می‌شود (Eloquent می‌تواند connection جدا برای هر model داشته باشد اما JOIN بین دیتابیس‌ها وجود ندارد). رابطه را با یک id و فراخوانی read model عوض کنید: ماژول سفارش‌ها از ماژول مشتری‌ها customersByIds($ids) را یک‌جا می‌خواهد که همان eager loading دستی است. هر ماژول migration های خودش و DB::transaction خودش را دارد (مرز یک connection).

میکروسرویس (Microservices): ORM از مرز شبکه رد نمی‌شود ​

رابطه نمی‌تواند از مرز سرویس عبور کند: ORM نمی‌تواند orders (سرویس A) را با customers (سرویس B) join کند. N+1 از SQL به HTTP می‌رود: حلقه‌ای که برای هر سفارش GET /customers/{id} می‌زند همان پنجره است، با latency ده‌ها میلی‌ثانیه و حالت‌های خرابی. با endpoint دسته‌ای (GET /customers?ids=1,2,3)، یک read model محلی که با eventها تغذیه می‌شود (بخش Outbox) یا aggregation در gateway حل کنید. هر سرویس ORM و DB::transaction خودش را دارد؛ اتمیک بودن بین سرویس‌ها saga می‌خواهد (بخش Saga) چون هیچ transaction ORM ای بین سرویس‌ها پخش نمی‌شود. عملیات bulk داخل سرویس هم باید eventهایی را منتشر کند که ORM دور زده: mass update هیچ event ای نمی‌فرستد، پس cache یا index جست‌وجوی پایین‌دست هرگز خبردار نمی‌شود؛ یک ردیف outbox را در همان transaction بنویسید.

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

داده توزیع‌شده: replica، cache و SQL توزیع‌شده ​

Read replica ها (Replication & Failover) خواندن بعد از نوشتن پنهان ORM را به باگ تبدیل می‌کنند: save() سپس redirect سپس find() ممکن است replica عقب‌مانده را بخواند. گزینهٔ sticky در connection در Laravel خواندن را در همان request بعد از نوشتن روی primary نگه می‌دارد؛ در Go با transaction یا pool صریح مسیر بدهید. cache دور ORM (بخش دام‌های caching) و نوشتن‌های bulk که event نمی‌فرستند ورودی‌های کهنه به جا می‌گذارند. روی SQL توزیع‌شده (CockroachDB، Spanner، YugabyteDB) یک N+1 هزینهٔ round trip بین منطقه‌ای دارد و transaction ممکن است با 40001 تکرار شود: ORM باید کل واحد کار را دوباره تلاش کند (بخش Distributed SQL). سطح isolation پیش‌فرض بین محصولات فرق دارد (CockroachDB: Serializable، PostgreSQL و Oracle: Read Committed، InnoDB: Repeatable Read) و همین تعیین می‌کند read-modify-write از راه ORM چه چیزی را از دست می‌دهد؛ بخش Isolation Levels.

مسیر مقیاس‌پذیری: ۱×، ۱۰×، ۱۰۰× ​

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

آزمایشگاه (Lab) ​

به دو terminal نیازی نیست؛ یک shell و یک psql. خروجی مورد انتظار در comment هاست.

آماده‌سازی.

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

آزمایش 1: با GORM یک N+1 بسازید، بشمارید و درستش کنید.

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

آزمایش 2: با Eloquent یک N+1 بسازید، بشمارید و درستش کنید. model ها و migration را از snippet ها اضافه کنید (php artisan migrate)، 200 نویسنده و 5,000 کتاب بسازید و در php artisan tinker اجرا کنید:

فایل‌های آزمایشگاه به ترتیب: model ها، migration و کلاس کمکی Lab.

php
<?php

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

namespace App\Models;

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

final class Author extends Model
{
    use HasFactory;

    protected $fillable = ['name'];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

namespace App\Lab;

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

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

        $work();

        return $count;
    }

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

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

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

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

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

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

        return $seen;
    }

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

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

آزمایش 3: chunk ردیف‌ها را جا می‌اندازد و chunkById نه. با UPDATE books SET in_stock = true; بازنشانی کنید و بعد:

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

معادل‌های Go این‌ها هستند: chunk.OffsetSweep(ctx, db, 100) (کمتر از 5,000 ردیف را می‌بیند) و chunk.KeysetSweep(ctx, db, 100) (5,000 را می‌بیند).

آزمایش 4: N+1 را از سمت سرور پیدا کنید.

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

آزمایش 5: bulk در برابر تک‌ردیفی. در tinker، زمان foreach (range(1, 5000) as $i) Book::create([...]) را با Book::insert($rows) در batch های 1,000 تایی مقایسه کنید: در یک container محلی ثانیه‌ها در برابر ده‌ها میلی‌ثانیه انتظار داشته باشید.

بدفهمی‌های رایج ​

باورواقعیت
«N+1 فقط در مقیاس بالا مهم است.»از همان نسخهٔ اول یک مالیات latency متناسب با ردیف‌های هر صفحه است؛ فقط در مقیاس دیده می‌شود
«Eager loading یعنی JOIN.»در Eloquent و Preload در GORM یک query دوم با IN است؛ شکل join همان Joins است
«Eager loading همیشه سریع‌تر است.»round trip را با حافظه معاوضه می‌کند؛ فقط آنچه رندر می‌کنید بارگذاری کنید و ستون‌ها را انتخاب کنید
«chunk برای به‌روزرسانی دسته‌ای امن است.»وقتی update شرط filter را عوض کند ردیف‌ها را جا می‌اندازد؛ از chunkById استفاده کنید
«cursor() می‌تواند eager load کند و حافظه نمی‌خورد.»eager load نمی‌کند و driver PDO ممکن است همهٔ ردیف‌ها را بافر کند
«upsert یک save() بهتر است.»event، cast، mutator و observer را رد می‌کند و unique index می‌خواهد
«mass update، eventهای model را فرا می‌خواند.»mass update و insert و upsert و delete هیچ event ای نمی‌فرستند
«متد من یک transaction است.»فقط اگر DB::transaction یا BeginTx نوشته باشید؛ وگرنه هر statement جدا commit می‌شود
«find(1) دو بار همان شیء را می‌دهد.»در Eloquent، GORM و Rails نه؛ فقط ORM های Data Mapper identity map دارند
«ORM جلوی SQL injection را می‌گیرد.»فقط برای مقدارهای bind شده؛ رشته‌های raw و شناسه‌ها با خودتان است
«soft delete فقط یک delete است.»ردیف در جدول‌ها، index ها، constraint های unique و backup ها می‌ماند
«رابطهٔ polymorphic کلید خارجی دارد.»نمی‌تواند؛ ردیف یتیم ممکن است
«timestamp یک لحظه را نگه می‌دارد.»timestamptz نگه می‌دارد؛ timestamp یک ساعت دیواری است
«mock کردن ORM، query را تست می‌کند.»فراخوانی را تست می‌کند؛ فقط دیتابیس واقعی SQL را تست می‌کند
«migration های خودکار امن‌اند.»مکانیکی‌اند: rename داده را حذف می‌کند، index قفل می‌گیرد، NOT NULL بازنویسی می‌کند
«repository باعث می‌شود ORM قابل تعویض باشد.»نوع‌های Eloquent معمولاً بیرون می‌زنند؛ فایده‌اش یک درز و جای کد query است

یادسپار (Cheat sheet) ​

موضوعچه چیزی را به خاطر بسپارید
N+11 query برای والدها + 1 به ازای هر والد؛ با with، Preload، join یا withCount درست می‌شود
loaderهای Eloquentwith، load، loadMissing، withCount، withSum، with('a.b') تودرتو، with('a:id,name') ستون‌های کلید را نگه می‌دارد
سخت‌گیریModel::shouldBeStrict(! app()->isProduction())؛ preventLazyLoading، handleLazyLoadingViolationUsing
GORMPreload، Joins (belongs-to/has-one)، Preload(clause.Associations)، Debug()، ToSQL، FindInBatches، CreateInBatches، transaction پیش‌فرض برای هر نوشتن
Hydrationستون را انتخاب کنید، pluck، toBase، DTO؛ model حافظه و CPU می‌خورد
جدول بزرگchunkById / lazyById وقتی به‌روز می‌کنید؛ lazy فقط‌خواندنی؛ cursor eager load نمی‌کند؛ offset جا می‌اندازد
Bulkinsert (بدون event)، upsert (unique index)، insertOrIgnore (خطا را پنهان می‌کند)، mass update (بدون event و بدون updated_at)
سقف‌ها65,535 bind parameter (PostgreSQL، MySQL)؛ batch های 500 تا 1,000 ردیفی؛ unnest یا COPY
Transactionپیش‌فرض autocommit؛ هر use case را در DB::transaction بپیچید؛ side effect بعد از commit
IdentityEloquent و GORM: identity map ندارند؛ Doctrine، Hibernate، SQLAlchemy: دارند
Raw SQLمقدار را bind کنید؛ شناسه را whitelist کنید؛ whereIntegerInRaw برای فهرست عدد صحیح
SQL بدIN بزرگ ← ANY(array)/join؛ زنجیرهٔ OR ← IN/UNION؛ whereHas ← plan را ببینید؛ LIKE '%x%' ← trigram
Soft deletepartial unique index با WHERE deleted_at IS NULL؛ job پاک‌سازی
Polymorphicبدون FK؛ enforceMorphMap؛ جدول‌های جدا با CHECK را بسنجید
زمانtimestamptz، ذخیره به UTC، نوشتن bulk timestamp نمی‌گذارد
Optimistic lockستون version و WHERE version = ?؛ تعداد ردیف‌های اثرگرفته را بررسی کنید
خواندن SQLtoRawSql، DB::listen، Debug()، pg_stat_statements، EXPLAIN (ANALYZE, BUFFERS)
تستموتور واقعی، assert تعداد query، strict mode در bootstrap تست

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — یک view در Blade برای 50 نویسنده $author->books->count() چاپ می‌کند. چند query اجرا می‌شود و دو راه‌حل بگویید. حیاتی ​

پاسخ

پاسخ: 51 تا: یکی برای نویسنده‌ها و یکی برای هر نویسنده. با Author::withCount('books') (و خواندن books_count) یا with('books') درست می‌شود؛ مسیر کد را با Model::preventLazyLoading() نگهبانی کنید. بخش N+1 و eager loading.

۲ — آیا Author::with('books') یک JOIN اجرا می‌کند؟ حیاتی ​

پاسخ

پاسخ: نه. query دوم ... FROM books WHERE author_id IN (...) را می‌زند و ردیف‌ها را در PHP گروه می‌کند. join همان Joins در GORM یا JOIN FETCH در Doctrine است. بخش Preload یا join.

۳ — رابطه را با with('books:title') باریک می‌کنید و وصل کردن شکست می‌خورد. چرا؟ مهم ​

پاسخ

پاسخ: رابطه برای تطبیق کتاب با نویسنده به ستون کلید و کلید خارجی نیاز دارد؛ id و author_id را هم select کنید: with('books:id,author_id,title').

۴ — jobی با Book::where('in_stock', true)->chunk(200, ...) مقدار in_stock = false را می‌گذارد و تمام می‌شود در حالی که ردیف‌هایی هنوز true اند. چه شد و چه چیزی را عوض می‌کنید؟ مهم ​

پاسخ

پاسخ: chunk با OFFSET صفحه‌بندی می‌کند؛ هر update ردیف‌ها را از filter بیرون برد و offset های بعدی ردیف‌های ندیده را جا انداختند. از chunkById یا lazyById استفاده کنید که با WHERE id > last صفحه می‌زنند. بخش chunking.

۵ — Book::where(...)->update([...]) نسبت به بارگذاری و ذخیرهٔ هر model چه چیزی را رد می‌کند؟ مهم ​

پاسخ

پاسخ: eventهای model (saving، saved، updating، updated) و observer ها، cast و mutator، و updated_at خودکار؛ یک statement اتمیک SQL است. بخش نوشتن bulk.

۶ — چرا insertOrIgnore می‌تواند خطرناک باشد؟ مهم ​

پاسخ

پاسخ: خطای کلید تکراری و بسته به موتور خطاهای دیگر را نادیده می‌گیرد؛ مستندات Laravel یادآور می‌شود strict mode در MySQL را دور می‌زند. ردیف رد‌شده از ردیف درج‌شده تشخیص داده نمی‌شود. upsert را ترجیح دهید یا تعداد اثرگرفته را بررسی کنید.

۷ — import 10,000 ردیفی در ردیف 6,000 crash می‌کند. با حلقهٔ save() و بدون transaction چند ردیف ذخیره شده و چطور همه‌یا‌هیچ‌اش می‌کنید؟ حیاتی ​

پاسخ

پاسخ: حدود 6,000: هر save() autocommit می‌شود. batch را در DB::transaction (یا BeginTx در Go) بپیچید تا crash همه چیز را برگرداند، و با upsert یا INSERT چندردیفی batch کنید. بخش transaction.

۸ — چرا Book::find(1) دوبار در Eloquent دو شیء می‌دهد و در Doctrine یکی؟ تکمیلی ​

پاسخ

پاسخ: EntityManager در Doctrine Identity Map و Unit of Work را پیاده می‌کند؛ Eloquent Active Record است و هیچ‌کدام را ندارد. بخش identity map و Active Record در برابر Data Mapper.

۹ — کدام‌ها injection پذیرند: where('name', $x)، whereRaw("name = '$x'")، orderBy($col) با ورودی کاربر، whereRaw('name = ?', [$x])؟ حیاتی ​

پاسخ

پاسخ: دومی و سومی. مقدارِ bind شده با ? امن است؛ concatenation نه، و نام ستون bind نمی‌شود پس whitelist کنید. بخش raw SQL.

۱۰ — چرا unique index روی users.email ثبت‌نام دوبارهٔ حساب soft-delete شده را می‌شکند و در PostgreSQL چه درستش می‌کند؟ مهم ​

پاسخ

پاسخ: index هنوز ردیف soft-delete شده را دارد. با partial unique index با WHERE deleted_at IS NULL عوضش کنید. بخش soft delete.

۱۱ — N+1 را از سمت دیتابیس چطور تشخیص می‌دهید؟ حیاتی ​

پاسخ

پاسخ: pg_stat_statements یک statement نرمال‌شده (... WHERE author_id = $1) با calls بسیار بالا و میانگین زمان ناچیز نشان می‌دهد. در اپلیکیشن: DB::listen، db.Debug() یا assert تعداد query. بخش خواندن SQL.

۱۲ — چرا mock کردن ORM جایگزین بدی برای دیتابیس واقعی در تست است؟ مهم ​

پاسخ

پاسخ: mock فراخوانی‌ها را بررسی می‌کند نه SQL را: N+1، نقض constraint، رفتار NULL و collation، قابلیت‌های خاص موتور و migration ها را نمی‌بیند. موتور واقعی و assert تعداد query به کار ببرید. بخش تست.

واژه‌نامه ​

اصطلاحمعنی
ORMنگاشت شیء-رابطه‌ای (Object-Relational Mapper): کتابخانه‌ای که جدول و ردیف را به کلاس و شیء نگاشت می‌کند
Impedance mismatchناهمخوانی مفهومی گراف شیء با schema رابطه‌ای (هویت، رابطه، وراثت، نوع)
N+1یک query برای N والد به‌علاوهٔ N query برای رابطه‌هایشان
Lazy loadingبارگذاری تنبل (Lazy loading): آوردن رابطه در اولین خواندن property
Eager loadingبارگذاری پیشاپیش (Eager loading): آوردن رابطه‌ها از قبل در تعداد ثابتی query
with / load / loadMissingEloquent: eager load پیش از query / روی model های موجود / فقط اگر بارگذاری نشده باشد
withCount / withSumEloquent: افزودن attribute تجمیعی با subquery (books_count، books_sum_price_cents)
Nested eager loadingwith('a.b.c'): یک query برای هر سطح
preventLazyLoadingمحافظ Eloquent که در lazy load خطای LazyLoadingViolationException می‌دهد
shouldBeStrictکلید Eloquent برای preventLazyLoading، preventSilentlyDiscardingAttributes و preventAccessingMissingAttributes
automaticallyEagerLoadRelationshipsگزینهٔ Eloquent که lazy load های model های هم‌خانواده را دسته‌ای می‌کند
Hydrationتبدیل ردیف‌های نتیجه به شیء model
DTOشیء انتقال داده (Data Transfer Object): struct ساده و کوچک برای یک خواندن
chunkپیمایش Eloquent با LIMIT/OFFSET؛ اگر حلقه filter را عوض کند ردیف جا می‌اندازد
chunkById / lazyByIdپیمایش با WHERE id > last؛ هنگام به‌روزرسانی امن است
lazychunk که در یک LazyCollection تخت شده
cursorیک query و هر بار یک model با generator؛ eager load نمی‌کند
Keyset pagingWHERE key > last ORDER BY key LIMIT n؛ موقعیت با مقدار، نه با شمارش
insertinsert چندردیفی Eloquent؛ بدون event و بدون timestamp
upsertدرج یا به‌روزرسانی در یک statement؛ unique index روی ستون‌های کلید می‌خواهد
insertOrIgnoreدرجی که خطای تکراری (و شاید خطاهای دیگر) را نادیده می‌گیرد
Mass updateModel::where(...)->update(...): یک UPDATE بدون eventهای model
Model eventssaving، saved، creating، updating و مانند آن که عملیات model می‌فرستد
Observerکلاسی که به eventهای model گوش می‌دهد
saveQuietly / withoutEventsذخیره یا اجرا بدون فرستادن eventهای model
Implicit transactiontransaction ضمنی: آنچه دیتابیس یا ORM دور یک statement یا نوشتن باز می‌کند
DB::transactionمرز transaction صریح Laravel با attempts برای تلاش دوباره
SkipDefaultTransactionتنظیم GORM که transaction هر نوشتن را برمی‌دارد
Identity Mapبرای هر ردیف در هر جلسه فقط یک شیء نگه می‌دارد
Unit of Workتغییرها را جمع می‌کند و در flush() می‌نویسد
Active Recordخود شیء model ذخیره می‌شود (Eloquent، Rails، Django)
Data Mappermapper جدا شیءهای ساده را ذخیره می‌کند (Doctrine، Hibernate، SQLAlchemy)
Repositoryرابط مجموعه‌مانند روی لایهٔ نگاشت
Query builderAPI روان که SQL می‌سازد بی‌آنکه رفتار دامنه را hydrate کند
Raw SQLSQL ای که خودتان می‌نویسید؛ مقدار را bind و شناسه را whitelist کنید
SQL injectionتبدیل شدن ورودی نامعتبر به متن SQL
whereIntegerInRawEloquent: فهرست عدد صحیح را به جای bind مستقیم در SQL می‌گذارد
ANY(array)شرط PostgreSQL که یک پارامتر آرایه می‌گیرد
Soft deleteعلامت زدن deleted_at به جای حذف ردیف
Partial indexindexی با WHERE؛ برای محدود کردن یکتایی به ردیف‌های زنده
Polymorphic relationرابطه‌ای که id بیگانه‌اش ممکن است به چند جدول اشاره کند، بدون FK
enforceMorphMapEloquent: به جای نام کلاس، نام کوتاه را در ستون نوع morph ذخیره می‌کند
timestamptzنوع timestamp در PostgreSQL که یک لحظه را نگه می‌دارد
Optimistic lockingقفل خوش‌بینانه: ستون version که در WHERE به‌روزرسانی بررسی می‌شود
AutoMigrateهمگام‌سازی schema در GORM؛ ابزار migration امن برای production نیست
toRawSqlEloquent: SQL با bindingهای جایگزین‌شده
DB::listenhook ای در Eloquent که برای هر statement اجراشده صدا زده می‌شود
Debug / ToSQL / DryRunراه‌های GORM برای دیدن SQL یا اجرا نکردن آن
Preload / JoinsGORM: eager loading با query جدا / بارگذاری با LEFT JOIN
pgxdriver و جعبه‌ابزار PostgreSQL برای Go؛ CopyFrom، Batch، CollectRows
sqlxافزونه‌های Go روی database/sql: scan به struct، پارامتر نام‌دار، In
sqlcتولید Go با نوع‌های امن از روی SQL
Entفریم‌ورک entity در Go با API گراف تولیدشده و edge های eager-loading
BunORM مبتنی بر SQL برای Go روی database/sql
DoctrineORM از نوع Data Mapper در PHP با identity map، unit of work و DQL
pg_stat_statementsافزونهٔ PostgreSQL برای شمارش و زمان هر statement
Testcontainersکتابخانه‌ای که container دیتابیس واقعی را برای تست بالا می‌آورد

منابع ​

ساخته‌شده توسط Morteza Negahi