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

在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

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度