Associations

Belongs To

  1. // `User` belongs to `Profile`, `ProfileID` is the foreign key
  2. type User struct {
  3. gorm.Model
  4. Profile Profile
  5. ProfileID int
  6. }
  7. type Profile struct {
  8. gorm.Model
  9. Name string
  10. }
  11. db.Model(&user).Related(&profile)
  12. //// SELECT * FROM profiles WHERE id = 111; // 111 is user's foreign key ProfileID

Specify Foreign Key

  1. type Profile struct {
  2. gorm.Model
  3. Name string
  4. }
  5. type User struct {
  6. gorm.Model
  7. Profile Profile `gorm:"ForeignKey:ProfileRefer"` // use ProfileRefer as foreign key
  8. ProfileRefer uint
  9. }

Specify Foreign Key & Association Key

  1. type Profile struct {
  2. gorm.Model
  3. Refer int
  4. Name string
  5. }
  6. type User struct {
  7. gorm.Model
  8. Profile Profile `gorm:"ForeignKey:ProfileID;AssociationForeignKey:Refer"`
  9. ProfileID int
  10. }

Has One

  1. // User has one CreditCard, UserID is the foreign key
  2. type User struct {
  3. gorm.Model
  4. CreditCard CreditCard
  5. }
  6. type CreditCard struct {
  7. gorm.Model
  8. UserID uint
  9. Number string
  10. }
  11. var card CreditCard
  12. db.Model(&user).Related(&card, "CreditCard")
  13. //// SELECT * FROM credit_cards WHERE user_id = 123; // 123 is user's primary key
  14. // CreditCard is user's field name, it means get user's CreditCard relations and fill it into variable card
  15. // If the field name is same as the variable's type name, like above example, it could be omitted, like:
  16. db.Model(&user).Related(&card)

Specify Foreign Key

  1. type Profile struct {
  2. gorm.Model
  3. Name string
  4. UserRefer uint
  5. }
  6. type User struct {
  7. gorm.Model
  8. Profile Profile `gorm:"ForeignKey:UserRefer"`
  9. }

Specify Foreign Key & Association Key

  1. type Profile struct {
  2. gorm.Model
  3. Name string
  4. UserID uint
  5. }
  6. type User struct {
  7. gorm.Model
  8. Refer uint
  9. Profile Profile `gorm:"ForeignKey:UserID;AssociationForeignKey:Refer"`
  10. }

Has Many

  1. // User has many emails, UserID is the foreign key
  2. type User struct {
  3. gorm.Model
  4. Emails []Email
  5. }
  6. type Email struct {
  7. gorm.Model
  8. Email string
  9. UserID uint
  10. }
  11. db.Model(&user).Related(&emails)
  12. //// SELECT * FROM emails WHERE user_id = 111; // 111 is user's primary key

Specify Foreign Key

  1. type Profile struct {
  2. gorm.Model
  3. Name string
  4. UserRefer uint
  5. }
  6. type User struct {
  7. gorm.Model
  8. Profiles []Profile `gorm:"ForeignKey:UserRefer"`
  9. }

Specify Foreign Key & Association Key

  1. type Profile struct {
  2. gorm.Model
  3. Name string
  4. UserID uint
  5. }
  6. type User struct {
  7. gorm.Model
  8. Refer uint
  9. Profiles []Profile `gorm:"ForeignKey:UserID;AssociationForeignKey:Refer"`
  10. }

Many To Many

  1. // User has and belongs to many languages, use `user_languages` as join table
  2. type User struct {
  3. gorm.Model
  4. Languages []Language `gorm:"many2many:user_languages;"`
  5. }
  6. type Language struct {
  7. gorm.Model
  8. Name string
  9. }
  10. db.Model(&user).Related(&languages, "Languages")
  11. //// SELECT * FROM "languages" INNER JOIN "user_languages" ON "user_languages"."language_id" = "languages"."id" WHERE "user_languages"."user_id" = 111

*With back-reference :

  1. // User has and belongs to many languages, use `user_languages` as join table
  2. // Make sure the two models are in different files
  3. type User struct {
  4. gorm.Model
  5. Languages []Language `gorm:"many2many:user_languages;"`
  6. }
  7. type Language struct {
  8. gorm.Model
  9. Name string
  10. Users []User `gorm:"many2many:user_languages;"`
  11. }
  12. db.Model(&language).Related(&users)
  13. //// SELECT * FROM "users" INNER JOIN "user_languages" ON "user_languages"."user_id" = "users"."id" WHERE ("user_languages"."language_id" IN ('111'))

Specify Foreign Key & Association Key

  1. type CustomizePerson struct {
  2. IdPerson string `gorm:"primary_key:true"`
  3. Accounts []CustomizeAccount `gorm:"many2many:PersonAccount;AssociationForeignKey:idAccount;ForeignKey:idPerson"`
  4. }
  5. type CustomizeAccount struct {
  6. IdAccount string `gorm:"primary_key:true"`
  7. Name string
  8. }

Polymorphism

Supports polymorphic has-many and has-one associations.

  1. type Cat struct {
  2. Id int
  3. Name string
  4. Toy Toy `gorm:"polymorphic:Owner;"`
  5. }
  6. type Dog struct {
  7. Id int
  8. Name string
  9. Toy Toy `gorm:"polymorphic:Owner;"`
  10. }
  11. type Toy struct {
  12. Id int
  13. Name string
  14. OwnerId int
  15. OwnerType string
  16. }

Note: polymorphic belongs-to and many-to-many are explicitly NOT supported, and will throw errors.

Association Mode

Association Mode contains some helper methods to handle relationship things easily.

  1. // Start Association Mode
  2. var user User
  3. db.Model(&user).Association("Languages")
  4. // `user` is the source, it need to be a valid record (contains primary key)
  5. // `Languages` is source's field name for a relationship.
  6. // If those conditions not matched, will return an error, check it with:
  7. // db.Model(&user).Association("Languages").Error
  8. // Query - Find out all related associations
  9. db.Model(&user).Association("Languages").Find(&languages)
  10. // Append - Append new associations for many2many, has_many, will replace current association for has_one, belongs_to
  11. db.Model(&user).Association("Languages").Append([]Language{languageZH, languageEN})
  12. db.Model(&user).Association("Languages").Append(Language{Name: "DE"})
  13. // Delete - Remove relationship between source & passed arguments, won't delete those arguments
  14. db.Model(&user).Association("Languages").Delete([]Language{languageZH, languageEN})
  15. db.Model(&user).Association("Languages").Delete(languageZH, languageEN)
  16. // Replace - Replace current associations with new one
  17. db.Model(&user).Association("Languages").Replace([]Language{languageZH, languageEN})
  18. db.Model(&user).Association("Languages").Replace(Language{Name: "DE"}, languageEN)
  19. // Count - Return the count of current associations
  20. db.Model(&user).Association("Languages").Count()
  21. // Clear - Remove relationship between source & current associations, won't delete those associations
  22. db.Model(&user).Association("Languages").Clear()