Skip to Content
fusion-orm
Relations

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>_type columns).

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

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.

On this page