GORM Associations: Related Data Not Saved
In this tutorial, you'll learn about GORM Associations: Related Data Not Saved. We cover key concepts, practical examples, and best practices.
GORM model associations -- Configure and save model associations (HasMany, BelongsTo, ManyToMany) in GORM.
The Problem
Nested structs in another struct does not automatically save associations. Use FullSaveAssociations or save associations separately.
Wrong
type Order struct {
ID uint
Items []Item
}
db.Create(&order) // Items not saved!
Output:
// Order created but Items array empty in DB
Right
type Order struct {
ID uint
Items []Item `gorm:"foreignKey:OrderID"`
}
order := Order{Items: []Item{{Name: "Widget"}}
db.Session(&gorm.Session{FullSaveAssociations: true}).Create(&order)
Output:
// Both Order and Item records created
Prevention
- Use association tags: foreignKey, references, many2many
- Use FullSaveAssociations session for saving nested
- Or save parent, then db.Model(&parent).Association("Items").Append(&items)
- Preload associations when querying
- Cascade deletes are not automatic
Common Mistakes with gorm associations
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro