Skip to Content
fusion-orm
Relations

Preload

Batched relation loading — one query per relation, nested paths, filtered preloads, polymorphic and many-to-many loading.

The contract

Preload(query, args...) is a chainable: it registers a relation (or a nested dotted path) to be loaded after the main query, in one batched query per relation — never one query per row.

// Preload requests a relation (or nested dotted path) to be loaded in one
// batched query after the main query. Args may be a func(*DB) *DB apply
// function, a SQL condition with args, or primary-key values.
func (db *DB) Preload(query string, args ...any) *DB {
	tx := db.getInstance()
	tx.Statement.Preloads = addPreload(tx.Statement.Preloads, strings.Split(query, "."), args)
	return tx
}

Preloading runs as a post-query step for Find, First, Take, Last, and the Association API's read paths. It is skipped under DryRun and on chains that already carry an error (preload.go:91).

Every relation kind, in one query

q := db.Model(&relUser{}).Preload("Profile").Preload("Posts.Comments").Preload("Team").Preload("Tags").Order("id")
var users []relUser
res := q.Find(&users)

After Find, users[0].Profile is a *relProfile, users[0].Posts is a []relPost whose entries each carry their Comments, users[0].Team is loaded, and users[0].Tags holds the two tags linked through the user_tags junction.

The test asserts the total statement count:

if got := counter.count(); got != 7 {
	t.Errorf("queries = %d, want 7 (root + 4 relations + nested + m2m junction)", got)
}

Those 7 queries break down exactly as:

#Query
1root SELECT from rel_users
2has-one Profile — rel_profiles WHERE user_id IN (1, 2, 3)
3has-many Posts — rel_posts WHERE user_id IN (1, 2, 3)
4nested Comments — rel_comments WHERE post_id IN (1, 2, 3)
5belongs-to Team — rel_teams WHERE id IN (1, 2)
6m2m junction — user_tags WHERE rel_user_id IN (1, 2, 3)
7m2m targets — rel_tags WHERE id IN (1, 2, 3)

The test also asserts a second invariant: exactly one statement touches rel_posts, no matter how many users were loaded — the N+1 guard (relation_test.go:187).

How batching works

For each relation, the loader collects the distinct foreign-key values from the already-fetched parent rows and issues a single IN query (preload.go:162):

  • has-one / has-many — keys come from the source's primary key; the child query filters fk IN (...).
  • belongs-to — keys come from the source's foreign-key field; the child query filters the target's primary key against them.
  • Results are grouped back onto the parents by key (assignRelation, preload.go:326). A parent with no match gets the zero value: pointer fields are set to nil, slices stay empty.

Missing matches stay nil

In the test above, carol has no profile row, so users[2].Profile == nil after the load (relation_test.go:171).

Nested dotted paths

Preload("Posts.Comments") registers Comments as a child of the Posts entry. The child query inherits the parent's preloaded rows as its sources, so comments are batched across all posts of all users in one statement (preload.go:186 — child.Statement.Preloads = entry.Children). Dotted paths of arbitrary depth follow the same rule.

Polymorphic preloads

For a relation tagged polymorphic:owner, the child query gains a type filter alongside the IN:

expr += " AND " + child.Statement.QuoteTo(polyType) + " = ?"
args = append(args, relValue)

The discriminator value is the polymorphic: tag value (see Polymorphic relations). Rows with a different owner_type are never mounted, even if their owner_id matches.

Many-to-many via the junction table

m2m loading is two queries, not one: first the junction rows for the source keys, then the target rows keyed by the collected references (loadM2M, preload.go:228):

SELECT "rel_user_id", "rel_tag_id" FROM "user_tags" WHERE "rel_user_id" IN (?, ?, ?)

Apply functions and conditions on the Tags preload apply to the target query, not the junction query.

Filtering a preload

Preload args come in two forms, dispatched by type (applyPreloadArgs, preload.go:73):

  1. Apply functions — any number of func(*DB) *DB values, each invoked with a fresh child session for the relation's query.
  2. Conditions — anything else is forwarded to applyConds (finisher_api.go:145): a SQL condition string with ? placeholders and args, or plain primary-key values.
db.Model(&polyOwner{}).
	Preload("Notes", func(tx *DB) *DB { return tx.Where("body LIKE ?", "%go%") }).
	First(&filtered, 1)
db.Model(&polyOwner{}).
	Preload("Notes", "body = ?", "sql note").
	First(&conditional, 1)

Both forms compose with nested paths: Preload("Posts.Comments", func(tx *DB) *DB { ... }) applies the function to the comments query.

Composite keys and the IN fallback

Relation loading builds WHERE fk IN (...) from the collected keys. Where a dialect lacks tuple-IN comparison, loading falls back to OR-equation batches, gated on the feature.CompositeIn capability bit (docs/ARCHITECTURE.md §11). Both in-tree dialects — SQLite (dialect/sqlite/sqlite.go:52) and PostgreSQL (dialect/postgres/postgres.go:56) — declare CompositeIn, so you will always see the plain IN form.

Interaction with soft delete and Unscoped

Preload queries filter soft-deleted child rows exactly like top-level queries. Unscoped() on the outer chain propagates to every relation query issued from it (preload.go:187):

// Unscoped disables soft-delete filtering and DELETE rewriting for the
// statement, including relation preloads issued from it.

Errors

Preloading an unknown name fails the chain with a wrapped ErrInvalidRelation before any query runs (preload.go:110):

db.AddError(fmt.Errorf("%w: %s.%s", ErrInvalidRelation, table.Name, entry.Field))

Next

On this page