GORM - association

1.1. BelongTo

type User struct {
  gorm.Model
  Profile   Profile // BelongTo, key = this.ProfileID
  ProfileID int
}

type Profile struct {
  gorm.Model
}

db.Model(&u).Related(&p)
//// SELECT * FROM profiles WHERE id = 111; // p.id = u.ProfileID

1.2. HasOne

type User struct {
    gorm.Model
    CreditCard   CreditCard // hasOne, key = c.UserID
}

type CreditCard struct {
    gorm.Model
    UserID   uint
}

var c CreditCard
db.Model(&u).Related(&c, "CreditCard")
//// SELECT * FROM credit_cards WHERE user_id = 123; // c.user_id = u.id

1.3. HasMany

  1. Many2Many

2. polymorphic

3. Association CRUD

Last updated