Associations
Model relationships.
Associations is a free Go Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Modeling Relationships
GORM associations map relationships between tables onto struct fields. The four kinds are has one, has many, belongs to, and many to many.
- Express foreign keys as struct fields
- Load related data automatically
- Create related records together
Has Many
A user has many posts. The parent holds a slice of children, and the child holds a foreign key back to the parent.
type User struct {
gorm.Model
Name string
Posts []Post
}
type Post struct {
gorm.Model
Title string
UserID uint
}Belongs To
From the childs perspective, a post belongs to a user. Add a User field plus the UserID foreign key to express it.
type Post struct {
gorm.Model
Title string
UserID uint
User User
}Has One
A has-one is like has-many but a single related record, such as a user having one profile. The child holds the foreign key.
type User struct {
gorm.Model
Profile Profile
}
type Profile struct {
gorm.Model
UserID uint
Bio string
}Many To Many
Users and roles relate many-to-many through a join table. The many2many tag names that join table, written as gorm:"many2many:user_roles;" in backticks after the Roles field.
type User struct {
gorm.Model
// Roles field tag: gorm:"many2many:user_roles;"
Roles []Role
}
type Role struct {
gorm.Model
Name string
}Preload
By default related data is not loaded. Preload tells GORM to fetch associations in a separate query, avoiding a separate manual lookup.
var user User
db.Preload("Posts").First(&user, 1)
fmt.Println(len(user.Posts))Nested Preload
You can preload across multiple levels with a dotted path, loading a users posts and each posts comments in one call chain.
db.Preload("Posts.Comments").First(&user, 1)A Runnable Association Simulation
GORM needs a database, so this runnable example models a has-many relationship and preloading using in-memory slices.
package main
import "fmt"
type Post struct {
ID int
UserID int
Title string
}
type User struct {
ID int
Name string
Posts []Post
}
func preload(u *User, all []Post) {
for _, p := range all {
if p.UserID == u.ID {
u.Posts = append(u.Posts, p)
}
}
}
func main() {
u := User{ID: 1, Name: "Ada"}
all := []Post{{1, 1, "Hello"}, {2, 1, "World"}, {3, 2, "Other"}}
preload(&u, all)
fmt.Printf("%s has %d posts\n", u.Name, len(u.Posts))
}Creating with Associations
If you set the slice field before Create, GORM inserts the parent and its children together and wires up the foreign keys automatically.
user := User{Name: "Ada", Posts: []Post{{Title: "Hi"}}}
db.Create(&user)The N Plus One Problem
Looping over parents and querying children per iteration causes one query per parent, the N+1 problem. Preload solves it by batching the related fetch into a single extra query.
Association Mode
The Association API appends, replaces, deletes, or clears related records without manual foreign key handling, for example db.Model(&user).Association("Posts").Append(&post).
Quick Check
Test your association knowledge.
Recap
You learned associations:
- has one, has many, belongs to, many2many model relationships
- Foreign keys are struct fields like UserID
- Preload loads associations and avoids N+1
- Creating a parent with children wires foreign keys
- Association mode appends, replaces, or clears relations
Frequently asked questions
Is the “Associations” lesson free?
Yes — the full text of “Associations” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Associations”?
Model relationships. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Associations” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.