Many-to-many
Junction tables — tag syntax, naming, AutoMigrate support, SetupJoinTable overrides, and idempotent Append.
Declaring the relation
A many-to-many relation tags the slice with rel:many2many and names the
junction table with many2many::
Tags []relTag `fusion:"rel:many2many,many2many:user_tags"`If you omit many2many:, the junction table name is inferred by sorting the
two table names and joining them with _, passed through the
Namer.JoinTableName hook (schema/relation.go:127):
rel.M2MName = tag.Get("many2many")
if rel.M2MName == "" {
names := []string{table.Name, join.Name}
sort.Strings(names)
rel.M2MName = table.namer.JoinTableName(names[0] + "_" + names[1])
} else {
rel.M2MName = table.namer.JoinTableName(rel.M2MName)
}The junction columns are derived from the two model names by plain
snake-casing — rel_user_id and rel_tag_id for the running example
(schema/relation.go:135). The junction table name flows through the
Namer.JoinTableName hook, so a custom naming strategy can prefix or
pluralize it; the column names themselves are not routed through the
Namer.
Single-column primary keys required
Both sides of a many2many must have a single-column primary key; the parser
rejects composite keys with a schema.ErrInvalidRelation error
(schema/relation.go:123).
Junction tables and AutoMigrate
AutoMigrate materializes every declared junction as a two-column table
whose composite primary key is both columns — so a duplicate pair cannot
be inserted at the storage layer (migrator/migrator.go:486):
// createJunctions materializes many-to-many junction tables declared by the
// model's relations. Each junction carries a composite primary key so a
// duplicate pair cannot be inserted at the storage layer.CREATE TABLE "user_tags" (
"rel_user_id" INTEGER NOT NULL,
"rel_tag_id" INTEGER NOT NULL,
PRIMARY KEY ("rel_user_id", "rel_tag_id")
)The column types mirror the related tables' primary-key types and skip
autoincrement entirely — junction columns never generate values themselves
(junctionTable, migrator/migrator.go:516). Existing junction tables are
left alone. (Added in 0.3.0; see CHANGELOG.md.)
Preloading
Loading tags for many users is two queries: one over the junction, one over the target table. See Preload for the query shapes and a worked example.
Appending is idempotent
Association("Tags").Append(&tag) checks whether the (source, target)
pair already exists before inserting:
// Re-appending an existing pair must not duplicate the junction row
// (GORM #5579/#7365 class): check first, insert only when missing.The existence check is a parameterized SELECT COUNT(*) built with the
dialect's bind vars, so it runs identically on SQLite and PostgreSQL
(junctionLinked, association.go:251). The same guard protects
association saves during Create callbacks.
If the appended value carries no primary key, the target record is created
first, then linked (association.go:181).
SetupJoinTable: custom junction models
When the junction needs more than two columns — or you want to control the
column mapping — register a custom join model with
SetupJoinTable(value, field, joinValue) (association.go:473):
type userTag struct {
UserID int64 `fusion:"column:rel_user_id"`
TagID int64 `fusion:"column:rel_tag_id"`
}
if err := db.SetupJoinTable(&relUser{}, "Tags", &userTag{}); err != nil {
t.Fatal(err)
}After the call, every m2m operation for relUser.Tags — preload, append,
delete, clear, and the association callbacks — reads and writes the custom
model's table and columns. Column resolution picks the fields named
<model>_id and <joinModel>_id through the naming strategy; failing
that, it falls back to the join model's first two distinct fields
(association.go:488). The join model is metadata for name resolution only.
Which table is used
The override replaces the spec returned by m2mSpec for exactly one
(model, field) pair. Preloads, Association mutations, and
deleteBeforeAssociations all consult it, so they stay consistent.