【问题标题】:Is it possible to omit FieldID in struct when using gorm?使用gorm时是否可以在struct中省略FieldID?
【发布时间】:2022-01-21 04:33:38
【问题描述】:
查看example from their documentation:
type User struct {
gorm.Model
Name string
CompanyID int
Company Company
}
type Company struct {
ID int
Name string
}
CompanyID 字段似乎相当多余。是否可以使用 Company 字段上的一些标签来摆脱它?
【问题讨论】:
标签:
mysql
sql
go
orm
go-gorm
【解决方案1】:
像这样更改User 定义就可以了:
type User struct {
gorm.Model
Name string
Company Company `gorm:"column:company_id"`
}
【解决方案2】:
您可以创建自己的BaseModel,而不是使用gorm.Model,例如
type BaseModel struct {
ID uint `gorm:"not null;AUTO_INCREMENT;primary_key;"`
CreatedAt *time.Time
UpdatedAt *time.Time
DeletedAt *time.Time `sql:"index"`
}
然后,在User,做这样的事情,基本上覆盖默认的Foreign Key
type User struct {
BaseModel
Name string
Company company `gorm:"foreignKey:id"`
}
和公司
type Company struct {
BaseModel
Name string
}