我想使用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查询后获得UserName,如何获取?我正在使用item.Username
,但错误显示item.UserName undefined (type []models.User has no field or method UserName)
最佳答案
[]
表示slice,这意味着item
不是单个用户,而是一部分用户,并且slices没有字段,它们具有存储在其中的各个实例的元素,要使用index expression访问这些元素(s[i]
)。可以将item[0].UserName
声明为单个用户,而不是将其声明为片。即item
,则可以使用selector expression item := model.User{}
。
关于mysql - 从Golang Gorm查询中获取选定的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61437536/