Skip to content

GORM Associations: Related Data Not Saved

DodaTech Updated 2026-06-24 1 min read

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
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

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead 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

**Difference between HasMany and BelongsTo?**

HasMany is on parent. BelongsTo is on child.

How do I save ManyToMany?

GORM auto-creates join table. Use gorm:"many2many:user_roles" tag.

Does GORM support polymorphic?

Yes. Use gorm:"polymorphic:Owner" tag.


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