go - Referencing GORM auto-generated fields in Go
问题描述
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?
解决方案
gorm.Model
是一个包含一些基本字段的结构,其中包括 fields ID
, CreatedAt
, UpdatedAt
, DeletedAt
.
推荐阅读
- c++ - 在 C++ 中的 unordered_map 中排序
- webgl - 为什么 iOS 15 上的 safari 对着色器属性名称很挑剔
- python - 估计两个二维点云之间的旋转
- javascript - Vue连接到firebase - 未捕获的FirebaseError:firebase.initilializeApp中未提供“projectId”
- flutter - 在颤动中塑造应用程序栏
- javascript - Comparing values in two arrays
- php - 警告:尝试访问第 41 行 C:\xampp\htdocs\crud\read.php 中 null 类型值的数组偏移量
- python - 如何使用 python 代码显示不相关的列而不绘图
- ssl - 带有 WS-Security\TLS\SSL 的公共 SOAP API
- python - 无法加载 spacy en_core_web_trf