Associations
Model relationships.
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
}