简体   繁体   中英

Get Selected value from Golang Gorm Query

I want to get user data after I do query using 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,
})

And here are my models

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

I just want to get the UserName after do query from gorm, how to get that? I'm using item.Username but, the error show that item.UserName undefined (type []models.User has no field or method UserName)

[] denotes a 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. ie item:= model.User{} then you can use the selector expression item.UserName .

You are trying to get UserName from slice of user that the problem. If email is a unique field database then you can use the user model only rather using slice of user.

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

Then you can access like username like item.UserName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM