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

Referencing GORM auto-generated fields in Go

我正在写我的第一个 API,所以请耐心等待。我正在使用 Go、Postgres 和 GORM 以及我仍在使用的许多其他东西,但我 运行 遇到了 GORM 的 AutoMigrate 问题。

最初我的用户结构是这样的:

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

当我 运行 db.AutoMigrate(&User{}) 它在我的用户 table 中自动生成一个 id 字段(以及几个日期字段),这是我想要的。我挂断的是弄清楚如何在我的应用程序中引用这些字段。我修改了我的用户结构,现在看起来像这样:

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

但是,当我访问存储的用户对象时,而不是链接两个 id 字段,如下所示:

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

现在有两个不同的字段,自动生成的和我自己的:

{
"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>
}

我意识到答案很可能就在我面前,一定有办法引用这些自动生成的字段,对吧?

gorm.Model是一个包含一些基本字段的结构体,其中包含字段IDCreatedAtUpdatedAtDeletedAt.

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