【发布时间】:2020-08-09 17:57:21
【问题描述】:
我想在使用 gorm 查询后获取用户数据
item := []models.User{}
if config.DB.First(&item, "email = ?", email).RecordNotFound() || len(item) == 0 {
c.JSON(500, gin.H{
"status": "error",
"message": "record not found"})
c.Abort()
return
}
c.JSON(200, gin.H{
"status": "success",
"data": item,
})
这是我的模型
type User struct {
gorm.Model
Stores []Store // to show that customer can have many stores
UserName string
FullName string
Email string `gorm:"unique_index"`
Password string
SocialID string
Provider string
Avatar string
Role bool `gorm:"default:0"`
HaveStore bool `gorm:"default:0"`
isActivate bool `gorm:"default:0"`
}
我只想在 gorm 查询后获取用户名,如何获取?我正在使用item.Username但是,错误显示item.UserName undefined (type []models.User has no field or method UserName)
【问题讨论】:
-
对于“找不到记录”错误,您应该将响应代码从 500 更改为 404。