【问题标题】: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
      }
      

      【讨论】:

        猜你喜欢
        • 2019-11-19
        • 1970-01-01
        • 2011-11-08
        • 1970-01-01
        • 2021-11-11
        • 2022-12-21
        • 1970-01-01
        • 2019-05-08
        • 2019-02-13
        相关资源
        最近更新 更多