Has Many

A has many association sets up a one-to-many connection with another model, unlike has one, the owner could have zero or many instances of models.

For example, if your application includes users and credit card, and each user can have many credit cards.

Declare

  1. // User has many CreditCards, UserID is the foreign key
  2. type User struct {
  3. gorm.Model
  4. CreditCards []CreditCard
  5. }
  6. type CreditCard struct {
  7. gorm.Model
  8. Number string
  9. UserID uint
  10. }

Retrieve

  1. // Retrieve user list with eager loading credit cards
  2. func GetAll(db *gorm.DB) ([]User, error) {
  3. var users []User
  4. err := db.Model(&User{}).Preload("CreditCards").Find(&users).Error
  5. return users, err
  6. }

Override Foreign Key

To define a has many relationship, a foreign key must exist. The default foreign key’s name is the owner’s type name plus the name of its primary key field

For example, to define a model that belongs to User, the foreign key should be UserID.

To use another field as foreign key, you can customize it with a foreignKey tag, e.g:

  1. type User struct {
  2. gorm.Model
  3. CreditCards []CreditCard `gorm:"foreignKey:UserRefer"`
  4. }
  5. type CreditCard struct {
  6. gorm.Model
  7. Number string
  8. UserRefer uint
  9. }

Override References

GORM usually uses the owner’s primary key as the foreign key’s value, for the above example, it is the User‘s ID,

When you assign credit cards to a user, GORM will save the user’s ID into credit cards’ UserID field.

You are able to change it with tag references, e.g:

  1. type User struct {
  2. gorm.Model
  3. MemberNumber string
  4. CreditCards []CreditCard `gorm:"foreignKey:UserNumber;references:MemberNumber"`
  5. }
  6. type CreditCard struct {
  7. gorm.Model
  8. Number string
  9. UserNumber string
  10. }

Polymorphism Association

GORM supports polymorphism association for has one and has many, it will save owned entity’s table name into polymorphic type’s field, primary key value into the polymorphic field

  1. type Dog struct {
  2. ID int
  3. Name string
  4. Toys []Toy `gorm:"polymorphic:Owner;"`
  5. }
  6. type Toy struct {
  7. ID int
  8. Name string
  9. OwnerID int
  10. OwnerType string
  11. }
  12. db.Create(&Dog{Name: "dog1", Toys: []Toy{{Name: "toy1"}, {Name: "toy2"}}})
  13. // INSERT INTO `dogs` (`name`) VALUES ("dog1")
  14. // INSERT INTO `toys` (`name`,`owner_id`,`owner_type`) VALUES ("toy1","1","dogs"), ("toy2","1","dogs")

You can change the polymorphic type value with tag polymorphicValue, for example:

  1. type Dog struct {
  2. ID int
  3. Name string
  4. Toys []Toy `gorm:"polymorphic:Owner;polymorphicValue:master"`
  5. }
  6. type Toy struct {
  7. ID int
  8. Name string
  9. OwnerID int
  10. OwnerType string
  11. }
  12. db.Create(&Dog{Name: "dog1", Toys: []Toy{{Name: "toy1"}, {Name: "toy2"}}})
  13. // INSERT INTO `dogs` (`name`) VALUES ("dog1")
  14. // INSERT INTO `toys` (`name`,`owner_id`,`owner_type`) VALUES ("toy1","1","master"), ("toy2","1","master")

CRUD with Has Many

Please checkout Association Mode for working with has many relations

Eager Loading

GORM allows eager loading has many associations with Preload, refer Preloading (Eager loading) for details

Self-Referential Has Many

  1. type User struct {
  2. gorm.Model
  3. Name string
  4. ManagerID *uint
  5. Team []User `gorm:"foreignkey:ManagerID"`
  6. }

FOREIGN KEY Constraints

You can setup OnUpdate, OnDelete constraints with tag constraint, it will be created when migrating with GORM, for example:

  1. type User struct {
  2. gorm.Model
  3. CreditCards []CreditCard `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
  4. }
  5. type CreditCard struct {
  6. gorm.Model
  7. Number string
  8. UserID uint
  9. }

You are also allowed to delete selected has many associations with Select when deleting, checkout Delete with Select for details