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条)

报告相同问题?

悬赏问题

  • ¥20 学生成绩管理系统设计
  • ¥15 来一个cc穿盾脚本开发者
  • ¥15 CST2023安装报错
  • ¥15 使用diffusionbert生成文字 结果是PAD和UNK怎么办
  • ¥15 有人懂怎么做大模型的客服系统吗?卡住了卡住了
  • ¥20 firefly-rk3399上启动卡住了
  • ¥15 如何删除这个虚拟音频
  • ¥50 hyper默认的default switch
  • ¥15 网站打不开,提示502 Bad Gateway
  • ¥20 基于MATLAB的绝热压缩空气储能系统代码咨询