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

By default polymorphic:<value> will prefix the column type and column id with <value>.
The value will be the table name pluralized.

  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 specify polymorphism properties separately using the following GORM tags:

  • polymorphicType: Specifies the column type.
  • polymorphicId: Specifies the column ID.
  • polymorphicValue: Specifies the value of the type.
  1. type Dog struct {
  2. ID int
  3. Name string
  4. Toys []Toy `gorm:"polymorphicType:Kind;polymorphicId:OwnerID;polymorphicValue:master"`
  5. }
  6. type Toy struct {
  7. ID int
  8. Name string
  9. OwnerID int
  10. Kind 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`,`kind`) VALUES ("toy1",1,"master"), ("toy2",1,"master")

In these examples, we’ve used a has-many relationship, but the same principles apply to has-one relationships.