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

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

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
}

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:

确定