从 Golang Gorm 查询中获取选定的值

Get Selected value from Golang Gorm Query

我想在使用 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)

[]表示slice, which means that item is not a single user but a slice of users, and slices don't have fields, they have elements which are the individual instances stored in them, to access these elements you use an index expression (s[i]). Either do item[0].UserName or declare item as a single user, not a slice. i.e. item := model.User{} then you can use the selector expressionitem.UserName.

您正试图从部分用户那里得到 UserName 问题所在。 如果电子邮件是一个独特的字段数据库,那么您可以只使用用户模型而不是使用用户切片。

item := models.User{}
config.DB.First(&item, "email = ?", email)

然后你可以像item.UserName

这样的用户名访问