drydaenth257216154 2018-07-26 08:26
浏览 436
已采纳

如何访问gorm.Model.ID?

So gorm.Model provides some base properties or fields:

ID        uint       `json:"-" gorm:"primary_key"`
CreatedAt time.Time  `json:"-"`
UpdatedAt time.Time  `json:"-"`
DeletedAt *time.Time `json:"-" sql:"index"`

and you can use it as so

type User struct {
  gorm.Model
  Name         string
  Email        string  `gorm:"type:varchar(100);unique_index"`
  Role         string  `gorm:"size:255"` // set field size to 255

}

So when I was working on my Model Controller(s) for delete (or anything where I needed to compare the ID)

This does not work, give me an error:

c.Ctx.DB.Delete(&models.Address{ID: id})

unknown field 'ID' in struct literal of type github.com/NlaakStudios/PASIT/models".Address

And, this does not work, give me an error:

 c.Ctx.DB.Delete(&models.Address{gorm.Model.ID: id})

invalid field name gorm.Model.ID in struct initializer id int

If I remove the gorm.Model and define the field myself in each model ... it works.

type User struct {
ID        uint       `json:"-" gorm:"primary_key"`
CreatedAt time.Time  `json:"-"`
UpdatedAt time.Time  `json:"-"`
DeletedAt *time.Time `json:"-" sql:"index"`
  Name         string
  Email        string  `gorm:"type:varchar(100);unique_index"`
  Role         string  `gorm:"size:255"` // set field size to 255
}

How do I access those four base fields?

  • 写回答

2条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥100 支付宝sdk原生链接转h5
      • ¥20 VS2019如何添加.mdf文件失败
      • ¥15 SeaTunnel多Transform配置问题
      • ¥15 消除字符串,求最短字符串长度
      • ¥20 有人做基于集员滤波的异常值处理相关的内容吗?(语言-matlab)
      • ¥30 matlab编程,用chatGPT帮助,但给出的code总是报错。
      • ¥15 离线安装VS2017出现报错
      • ¥50 opengl2怎么将梯形的纹理映射在矩形上面不变形
      • ¥15 起终点不同的tsp旅行商问题
      • ¥15 博途V16变频器CU320-2pn版本为2.34的gsd文件