0PricingLogin
Go Academy · Lesson

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
}

All lessons in this course

  1. Models and AutoMigrate
  2. CRUD Operations
  3. Associations
  4. Hooks and Scopes
← Back to Go Academy