在使用gorm时,是否可以省略结构体中的FieldID?

huangapple go评论112阅读模式
英文:

Is it possible to omit FieldID in struct when using gorm?

问题

看一个他们文档中的例子

  1. type User struct {
  2. gorm.Model
  3. Name string
  4. CompanyID int
  5. Company Company
  6. }
  7. type Company struct {
  8. ID int
  9. Name string
  10. }

CompanyID 字段似乎有些多余。是否可以使用 Company 字段上的一些标签来摆脱它?

英文:

Looking at an example from their documentation:

  1. type User struct {
  2. gorm.Model
  3. Name string
  4. CompanyID int
  5. Company Company
  6. }
  7. type Company struct {
  8. ID int
  9. Name string
  10. }

CompanyID field seems rather redundant. Is it possible to get rid of it using some tags on Company field instead?

答案1

得分: 1

User的定义更改为以下内容即可解决问题:

  1. type User struct {
  2. gorm.Model
  3. Name string
  4. Company Company `gorm:"column:company_id"`
  5. }
英文:

Changing User definition like this did the trick:

  1. type User struct {
  2. gorm.Model
  3. Name string
  4. Company Company `gorm:"column:company_id"`
  5. }

答案2

得分: 0

你可以创建自己的BaseModel,而不是使用gorm.Model,例如:

  1. type BaseModel struct {
  2. ID uint `gorm:"not null;AUTO_INCREMENT;primary_key;"`
  3. CreatedAt *time.Time
  4. UpdatedAt *time.Time
  5. DeletedAt *time.Time `sql:"index"`
  6. }

然后,在User结构体中,可以像这样做,基本上是覆盖默认的Foreign Key

  1. type User struct {
  2. BaseModel
  3. Name string
  4. Company company `gorm:"foreignKey:id"`
  5. }

还有Company结构体:

  1. type Company struct {
  2. BaseModel
  3. Name string
  4. }
英文:

You can create your own BaseModel instead of using gorm.Model, for example

  1. type BaseModel struct {
  2. ID uint `gorm:"not null;AUTO_INCREMENT;primary_key;"`
  3. CreatedAt *time.Time
  4. UpdatedAt *time.Time
  5. DeletedAt *time.Time `sql:"index"`
  6. }

Then, in the User, do something like this, basically overriding the default Foreign Key

  1. type User struct {
  2. BaseModel
  3. Name string
  4. Company company `gorm:"foreignKey:id"`
  5. }

And the Company

  1. type Company struct {
  2. BaseModel
  3. Name string
  4. }

huangapple
  • 本文由 发表于 2021年12月19日 04:31:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/70406904.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定