Skip to Content
fusion-orm
Relations

Inline joins

Joins("Profile") renders LEFT JOINs for has-one and belongs-to relations; raw SQL joins and alias__column scanning.

Two kinds of Joins

Joins(query, args...) accepts both a named relation and a raw SQL join. The dispatch is by prefix: anything starting with JOIN, LEFT, RIGHT, INNER, or CROSS is treated as raw SQL; everything else is a relation name (chainable_api.go:88).

// Joins adds a raw JOIN expression, or LEFT JOINs a named has-one/belongs-to
// relation and selects its columns as alias__column for dotted scanning.
func (db *DB) Joins(query string, args ...any) *DB {
	tx := db.getInstance()
	q := strings.TrimSpace(query)
	upper := strings.ToUpper(q)
	if strings.HasPrefix(upper, "JOIN ") || strings.HasPrefix(upper, "LEFT ") ||
		strings.HasPrefix(upper, "RIGHT ") || strings.HasPrefix(upper, "INNER ") ||
		strings.HasPrefix(upper, "CROSS ") {
		tx.Statement.Joins = append(tx.Statement.Joins, joinEntry{
			Raw: clause.Expr(q, args...), HasRaw: true,
		})
	} else {
		tx.Statement.Joins = append(tx.Statement.Joins, joinEntry{Relation: q})
	}
	return tx
}

Named relation joins

A named join expands to a LEFT JOIN at build time (applyJoins, joins.go:45). The alias is the lowercased relation name:

db.Model(&relUser{}).
	Joins("Profile").Joins("Team").
	Order("rel_users.id").
	Find(&users)
SELECT "rel_users"."id" AS "id", "rel_users"."name" AS "name", "rel_users"."team_id" AS "team_id", "profile"."id" AS "profile__id", "profile"."user_id" AS "profile__user_id", "profile"."bio" AS "profile__bio" FROM "rel_users" LEFT JOIN "rel_profiles" AS "profile" ON "rel_users"."id" = "profile"."user_id"

Inline joins support has-one and belongs-to only

Requesting a has-many or many2many relation by name fails the chain with a wrapped ErrInvalidRelation — joins.go:75 returns "inline joins support has-one and belongs-to only". Use Preload for collections.

After the query, the joined columns are mounted back onto the struct's relation fields — users[0].Profile is a full *relProfile (relation_test.go:211).

Column selection and alias__column scanning

When you have not called Select yourself, applyJoins qualifies every root column (rel_users.id AS id) and aliases every joined column as alias__column (joins.go:114):

for _, rel := range joined {
	alias := strings.ToLower(rel.Name)
	for _, field := range rel.JoinTable.Fields {
		cols = append(cols,
			q.QuoteTo(alias+"."+field.DBName)+" AS "+q.QuoteTo(alias+"__"+field.DBName))
	}
}

The scanner splits result columns on __ and mounts them into the nested field (scan.go:34). This works with your own aliases too:

res := db.Model(&scanOwner{}).
	Select(`id, name, 'mounted' AS profile__bio`).
	Scan(&owners)
// owners[0].Profile.Bio == "mounted"

Empty joins stay nil

A LEFT JOIN row whose joined columns are all NULL would otherwise mount a zero struct. pruneJoinedRelations clears such pointer fields back to nil after scanning (joins.go:12), so carol's missing profile reads as nil, not &relProfile{} (relation_test.go:214).

Soft delete is honored

The ON clause gains the joined table's soft-delete condition unless the chain is Unscoped, so a soft-deleted profile does not come back through a join (joins.go:94, GORM #6998 class):

// Inline joins must filter soft-deleted relation rows the same way
// preload does, otherwise a deleted profile still loads (GORM #6998).

Raw SQL joins

Any Joins argument beginning with a join keyword is spliced into the statement verbatim, args included:

db.Model(&relUser{}).
	Joins(`LEFT JOIN rel_profiles AS p ON p.user_id = rel_users.id`).
	Where("p.bio = ?", "a").
	Find(&raw)

Raw joins are deduplicated by their SQL text and never touched by the relation machinery — no alias rewriting, no scanning mounts, no soft-delete rewriting. Filter with ordinary Where on the alias.

Preload vs Joins

PreloadJoins("Profile")
Queriesone extra per relationnone — single statement
Supported kindsall four, plus polymorphic and nested pathshas-one, belongs-to only
Loaded valuefull objects, including nested relationscolumns scanned via alias__column into the relation field
Filteringapply functions / conditions on the child queryany SQL in the join or Where
Collectionsyes (has-many, many2many)no

Reach for Joins when you need to filter or sort the root by columns of the related table in one statement; reach for Preload when you need the related objects themselves, especially several relations at once.

Next

On this page