InfoSphere/GORM 中文版/ 返回书籍
Associations

Polymorphism

qianmoQqianmoQ· 更新于 2026-09-14· 阅读 3 分钟· 0 次阅读

登录后可跨设备保存划线和私人笔记登录

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.

type Dog struct {
  ID   int
  Name string
  Toys []Toy `gorm:"polymorphic:Owner;"`
}

type Toy struct {
  ID        int
  Name      string
  OwnerID   int
  OwnerType string
}

db.Create(&Dog{Name: "dog1", Toys: []Toy{{Name: "toy1"}, {Name: "toy2"}}})

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.
type Dog struct {
  ID   int
  Name string
  Toys []Toy `gorm:"polymorphicType:Kind;polymorphicId:OwnerID;polymorphicValue:master"`
}

type Toy struct {
  ID        int
  Name      string
  OwnerID   int
  Kind      string
}

db.Create(&Dog{Name: "dog1", Toys: []Toy{{Name: "toy1"}, {Name: "toy2"}}})

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

GitHub tag (latest SemVer)

评论

登录后参与评论

正在加载评论…