英文:
Is it possible to omit FieldID in struct when using gorm?
问题
看一个他们文档中的例子:
type User struct {
gorm.Model
Name string
CompanyID int
Company Company
}
type Company struct {
ID int
Name string
}
CompanyID
字段似乎有些多余。是否可以使用 Company
字段上的一些标签来摆脱它?
英文:
Looking at an example from their documentation:
type User struct {
gorm.Model
Name string
CompanyID int
Company Company
}
type Company struct {
ID int
Name string
}
CompanyID
field seems rather redundant. Is it possible to get rid of it using some tags on Company
field instead?
答案1
得分: 1
将User
的定义更改为以下内容即可解决问题:
type User struct {
gorm.Model
Name string
Company Company `gorm:"column:company_id"`
}
英文:
Changing User
definition like this did the trick:
type User struct {
gorm.Model
Name string
Company Company `gorm:"column:company_id"`
}
答案2
得分: 0
你可以创建自己的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"`
}
还有Company
结构体:
type Company struct {
BaseModel
Name string
}
英文:
You can create your own BaseModel
instead of using gorm.Model
, for example
type BaseModel struct {
ID uint `gorm:"not null;AUTO_INCREMENT;primary_key;"`
CreatedAt *time.Time
UpdatedAt *time.Time
DeletedAt *time.Time `sql:"index"`
}
Then, in the User
, do something like this, basically overriding the default Foreign Key
type User struct {
BaseModel
Name string
Company company `gorm:"foreignKey:id"`
}
And the Company
type Company struct {
BaseModel
Name string
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论