The Association API
Find, Append, Replace, Delete, Clear, and Count on a single relation of a single record.
Getting a handle
db.Model(&user).Association("Field") returns an *Association bound to
one relation of one record (association.go:24):
// Association operates on one relation of a single model. It mirrors gorm's
// db.Association(column) surface with error-returning finishers.assoc := db.Model(&carol).Association("Profile")
if err := assoc.Append(&relProfile{Bio: "carol bio"}); err != nil {
t.Fatalf("Append profile: %v", err)
}The model must be a single struct — a slice or an unknown field name fails
the chain with ErrInvalidValue / ErrInvalidRelation
(association.go:33). Operations on a struct whose primary key is zero fail
with ErrInvalidValue at Append time (association.go:153). Every method
returns an error (or (int64, error) for Count) rather than relying on
the chain's error slot alone.
The methods
| Method | Semantics | Source |
|---|---|---|
Find(dest) | Load the relation into dest | association.go:57 |
Append(values...) | Create missing records, then link | association.go:104 |
Replace(values...) | Clear() then Append(values...) | association.go:274 |
Delete(values...) | Unlink (and for has-*, delete) the given records | association.go:286 |
Clear() | Unlink everything without deleting targets | association.go:361 |
Count() | (int64, error) — number of related records | association.go:418 |
Find
Find runs the same batched loader Preload uses, on this one record, and
assigns into dest (association.go:57). It accepts the natural shapes:
*relProfile for a pointer relation, *[]relPost for a slice relation.
Because it flows through loadRelation, an Unscoped() chain also applies
to it, and polymorphic/m2m filters behave exactly like preloads.
var team relTeam
if err := db.Model(&carol).Association("Team").Find(&team); err != nil || team.Name != "ops" {
t.Errorf("belongs-to Find = %+v, %v", team, err)
}Find on a belongs-to follows the foreign key — carol's TeamID is resolved
to its rel_teams row.
Append
Append is a create-and-link operation whose exact behavior depends on the
relation kind (linkOne, association.go:134):
- belongs-to — if the target has a primary key, it is written to the source's foreign-key field; if not, the target record is created first and its new key written back.
- has-one / has-many — the source's primary key is written to the
child's foreign key, then the child is saved (
association.go:150). - many2many — the child is created only if it lacks a primary key (or
FullSaveAssociationsis set), then a junction row is inserted; re-appending an existing pair is a no-op (GORM #5579).
For has-one/has-many, a child that already carries a primary key is
updated by primary key instead of duplicated (GORM #6119 class,
association.go:216). With FullSaveAssociations set, it is saved with
Save instead (association.go:213).
posts := db.Model(&carol).Association("Posts")
if err := posts.Append(&relPost{Title: "p4"}, &relPost{Title: "p5"}); err != nil {
t.Fatalf("Append posts: %v", err)
}
// carol now owns p4 and p5: user_id written back, two rows insertedReplace
Replace clears the relation, then appends the given values
(association.go:274):
if err := db.Model(&carol).Association("Posts").Replace(&relPost{Title: "only"}); err != nil {
t.Fatalf("Replace posts: %v", err)
}
// Count() == 1For has-one/has-many, the old children are unlinked, not deleted —
Clear nulls their foreign keys — and the new values are appended.
Delete
Delete(values...) removes values from the relation, with kind-specific
mechanics (association.go:286):
- many2many — deletes the junction rows for the pairs; the tag records themselves survive.
- has-one / has-many — deletes the related records by primary key.
- belongs-to — zeroes the foreign-key field on the in-memory source struct only; no database write is issued.
- With no arguments it delegates to
Clear.
if err := db.Model(&carol).Association("Tags").Delete(&tag); err != nil {
t.Fatalf("Delete tag: %v", err)
}
// junction pair (carol, tag 3) removed; tag 3 still existsClear
Clear unlinks everything without deleting the related records
(association.go:361):
- many2many —
DELETE FROM user_tags WHERE rel_user_id = ?. - has-one / has-many — an
UPDATEthat nulls the child foreign key (association.go:396), scoped to the type column for polymorphic relations. - belongs-to — zeroes the foreign-key field on the in-memory struct
(
association.go:366).
if err := db.Model(&carol).Association("Profile").Clear(); err != nil {
t.Fatalf("Clear profile: %v", err)
}
// Count() == 0; the profile row still exists with user_id = NULLBelongs-to Clear is in-memory only
Clear and Delete on a belongs-to relation reset the foreign key on the
Go struct so you can persist it yourself; the library issues no UPDATE for
that column.
Count
Count loads the relation (same path as Find) and counts in memory:
len(slice) for has-many/many2many, 1 or 0 for pointer relations
(association.go:418):
if n, err := db.Model(&carol).Association("Profile").Count(); err != nil || n != 1 {
t.Errorf("profile count = %d, %v", n, err)
}A full walkthrough
The API test exercises every kind against one record — carol, user 3
(relation_test.go:230):
var carol relUser
db.First(&carol, 3)
db.Model(&carol).Association("Profile").Append(&relProfile{Bio: "carol bio"})
// has-one: profile row created, profile.user_id = 3 written back
db.Model(&carol).Association("Profile").Find(&profile) // Bio == "carol bio"
db.Model(&carol).Association("Profile").Count() // 1
db.Model(&carol).Association("Posts").Append(&relPost{Title: "p4"}, &relPost{Title: "p5"})
// has-many: two posts created with user_id = 3
db.Model(&carol).Association("Posts").Replace(&relPost{Title: "only"})
// p4 and p5 unlinked (user_id nulled), "only" created: Count() == 1
db.Model(&carol).Association("Tags").Append(&tag) // m2m: junction row
db.Model(&carol).Association("Tags").Delete(&tag) // junction row removed
db.Model(&carol).Association("Profile").Clear() // profile.user_id nulled
db.Model(&carol).Association("Team").Find(&team) // belongs-to follow
db.Model(&carol).Association("Team").Clear() // carol.TeamID == 0Hooks and re-entrancy
Records created through Append are saved on internal sessions with
SkipHooks set and the fusion:skip_associations guard armed
(association.go:197), so association saving never recurses into the
callback pipeline for the child rows. DryRun chains skip association
callbacks entirely (association_callbacks.go:11).