Association callbacks
What Create and Delete do to related records — FK write-back, cascade deletes, junction maintenance, and FullSaveAssociations.
The two save phases
Create (and Save, Updates) runs association saving in two callback
phases (association_callbacks.go:104):
- Before the root insert — belongs-to relations are resolved first, so
their foreign keys are available when the root row is written
(
saveBeforeAssociations). - After the root insert — has-one, has-many, and many2many are linked
once the root's primary key exists (
saveAfterAssociations).
// saveBeforeAssociations resolves belongs-to links before the root row is
// written, so their foreign keys are available for INSERT.Both phases go through the same linkOne machinery as the
Association API, so the semantics
match: create missing children, write foreign keys back, insert junction
rows, skip already-linked pairs.
The phases are fixed positions in the CRUD chains — Update runs them too
(callbacks/chain.go:8):
// Create is the default create chain.
func Create() []string {
return []string{
"fusion:begin_tx", "fusion:before_create",
"fusion:save_before_associations", "fusion:create",
"fusion:save_after_associations", "fusion:after_create",
"fusion:commit_or_rollback",
}
}If a belongs-to foreign key is already set on the struct, the phase leaves
it alone — it does not re-save or re-create the referenced record
(association_callbacks.go:124).
Create with associations: before and after
dave := &relUser{
Name: "dave",
Profile: &relProfile{Bio: "d"},
Posts: []relPost{{Title: "d1"}, {Title: "d2"}},
Tags: []relTag{{Name: "fresh"}},
}
if err := db.Create(dave).Error; err != nil {
t.Fatalf("Create with associations: %v", err)
}Before: dave.ID == 0, no profile/post rows, no fresh tag, no junction
entries.
After (asserted at relation_test.go:338):
dave.IDis backfilled.dave.Profile.UserID == dave.IDand everydave.Posts[i].UserID == dave.ID— foreign keys written back onto your structs, not just the rows.- One
rel_profilesrow, tworel_postsrows. - The
freshtag did not exist, so it is created, and auser_tagsjunction row links it to dave.
Reloading through preloads returns the full graph (relation_test.go:342):
db.Model(&relUser{}).Preload("Profile").Preload("Posts").Preload("Tags").
First(&loaded, dave.ID)
// loaded.Profile.Bio == "d", len(loaded.Posts) == 2, len(loaded.Tags) == 1Belongs-to is created first
eve := &relUser{Name: "eve", Team: &relTeam{Name: "newteam"}}
if err := db.Create(eve).Error; err != nil {
t.Fatalf("Create belongs-to: %v", err)
}
// eve.TeamID is backfilled from the newly created team rowThe newteam team is inserted before eve's row, its new primary key is
written back to eve.TeamID, and eve's INSERT carries the key
(relation_test.go:355).
Delete cascades — by kind
Delete on a root runs deleteBeforeAssociations
(association_callbacks.go:176). The action depends on the relation kind:
| Kind | What happens to related data |
|---|---|
| has-one / has-many | dependent rows are deleted (DELETE FROM child WHERE fk = ?, plus the type filter for polymorphic) |
| many2many | junction rows for the source are deleted; the tags themselves survive |
| belongs-to | nothing — the referenced record is untouched |
if err := db.Delete(&relUser{}, dave.ID).Error; err != nil {
t.Fatalf("Delete: %v", err)
}
// dave's posts are gone:
db.Model(&relPost{}).Where("user_id = ?", dave.ID).Count(&count) // 0The dependent delete honors soft delete — it issues a normal Delete on the
child session, so a soft-deletable child model is soft-deleted, not hard
deleted. The has-one/has-many cleanup arms the fusion:skip_associations
guard on its session (association_callbacks.go:215), so the cascade never
recurses; the junction delete targets a table with no relations, so it is
inherently inert.
FullSaveAssociations
By default, an associated record that already carries a primary key is
linked, not re-inserted: has-one/has-many children are updated by primary
key with Updates (non-zero fields), m2m targets are only connected. Setting
Session{FullSaveAssociations: true} changes that save to a full Save —
the associated record is updated with all its fields, zero fields
included (fusion.go:99):
// FullSaveAssociations makes association saves use Save (not Create) for
// records that already carry a primary key.frank := &relUser{Name: "frank", Tags: []relTag{{ID: 1, Name: "renamed"}}}
if err := db.Session(&Session{FullSaveAssociations: true}).Create(frank).Error; err != nil {
t.Fatal(err)
}
// tag 1 now has Name == "renamed"; rel_tags still has 3 rows —
// no duplicate insertThe flag flows into every association save, both the callback pipeline and
the direct Association API (association_callbacks.go:123).
Guards and knobs
DryRun— association callbacks are skipped entirely; a dry-runCreaterenders SQL for the root only (association_callbacks.go:12).- Internal re-entrancy — child rows written by the association machinery
run on sessions with
Statement.SkipHooksset and thefusion:skip_associationsguard armed, so they never re-trigger association saving (association.go:197). Unscoped— affects reads (preload/join filtering), not the save or delete callbacks themselves.
No join-table migration needed
Because the callbacks only ever INSERT into the junction table via the
resolved spec, a junction created by AutoMigrate (composite-PK, two
columns) or mapped through SetupJoinTable works identically — nothing in
the callback path assumes a particular junction shape beyond the two
columns.