dongping5230 2018-04-29 01:28
浏览 281
已采纳

在Go中引用GORM自动生成的字段

I'm writing my first API, so bear with me. I am using Go, Postgres and GORM and a slew of other things I'm still picking up but I ran into an issue with GORM's AutoMigrate.

Initially my User struct looked like this:

type User struct {
    gorm.Model
    Email    string `gorm:"unique" json:"email"`
    Password string `json:"password"`
}

And when I ran db.AutoMigrate(&User{}) It auto-generated an id field in my User table (along with several date fields), which I wanted. What I am hung up on is figuring out how to reference these fields in my app. I have modified my User struct to now look like this:

type User struct {
    gorm.Model
    ID       int    `gorm:"primary_key" json:"id"`
    Email    string `gorm:"unique" json:"email"`
    Password string `json:"password"`
}

But instead of linking the two id fields, when I access the stored user object as shown:

user := model.User{}
if err := db.First(&user, model.User{Email: email}).Error; err != nil {
    respondError(w, http.StatusNotFound, err.Error())
    return nil
}

there are now two distinct fields, the auto-generated and my own:

{
"ID": 2,
"CreatedAt": "2018-04-28T21:14:20.828547-04:00",
"UpdatedAt": "2018-04-28T21:14:20.828547-04:00",
"DeletedAt": null,
"id": 0,
"email": "joeynelson@gmail.com",
"password": <hash>
}

I realize the answer is likely right in front of my face, there must be a way to reference these auto-generated fields, right?

  • 写回答

1条回答 默认 最新

  • douzhi8488 2018-04-29 02:16
    关注

    gorm.Model is a struct including some basic fields, which including fields ID, CreatedAt, UpdatedAt, DeletedAt.

    Reference: http://gorm.io/docs/conventions.html#gorm-Model

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据