Relations
Preload, inline joins, many-to-many, polymorphic relations, and the Association API.
fusion-orm supports four relation kinds plus polymorphic has-many, all
declared with a single rel: struct tag:
- has-one — the target table carries a foreign key back to the source.
- has-many — the target table carries a foreign key back to the source, and the Go field is a slice.
- belongs-to — the source table carries the foreign key.
- many2many — a junction table links the two sides.
- polymorphic — a has-one/has-many variant where the target also stores a
type discriminator (
<name>_id/<name>_typecolumns).
Relations are parsed once into a cached schema.Relation and consumed by
four independent features: batched Preload, inline Joins, the
Association API, and association callbacks that save and delete related
records alongside the root.
The running example
Every page in this section uses the same model family: a user with a has-one profile, has-many posts (each with has-many comments), a belongs-to team, and a many-to-many tag list.
type relUser struct {
ID int64 `fusion:"pk,autoincrement"`
Name string
Profile *relProfile `fusion:"rel:has-one,foreignKey:UserID"`
Posts []relPost `fusion:"rel:has-many,foreignKey:UserID"`
TeamID int64
Team *relTeam `fusion:"rel:belongs-to,foreignKey:TeamID"`
Tags []relTag `fusion:"rel:many2many,many2many:user_tags"`
}The related models are plain structs — relProfile, relPost (which nests
Comments), relTeam, and relTag — defined the same way in
relation_test.go:26.
What's covered
Preload
Batched loading: one query per relation, nested dotted paths, filtered preloads, polymorphic and many-to-many loading.
Inline joins
Joins("Profile") LEFT JOINs a relation and mounts columns via
alias__column scanning; has-one and belongs-to only.
Many-to-many
Junction tables: naming, AutoMigrate support, and SetupJoinTable for
custom junction models.
Polymorphic relations
polymorphic:owner — one notes table pointing back at many owner types.
The Association API
Find, Append, Replace, Delete, Clear, and Count on a single
relation.
Association callbacks
What Create and Delete do to related records, and FullSaveAssociations.
Scope note
SQLite and PostgreSQL are the supported dialects. Relations require single-column primary keys on both sides; composite keys on a relation participant are rejected at parse time with a clear error.