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

如何访问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条回答 默认 最新

  • dtrhd2850 2018-07-26 18:15
    关注

    You're very close in your last example. You can remove the gorm.Model inheritance from your struct if you want/need (I personally do that for clarity), but to access that value you'd just need to build up your struct a little more. For example...

    type Address struct {
        gorm.Model
        Name         string
        Email        string  `gorm:"type:varchar(100);unique_index"`
        Role         string  `gorm:"size:255"` // set field size to 255
    }
    
    c.Ctx.DB.Delete(&models.Address{gorm.Model: gorm.Model{ID: id}})
    

    Give that a try and see if that works for you. Alternatively revert to your method without inheriting the gorm.Model

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置