arthas
arthas

Reputation: 13

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.Usernamebut, the error show that item.UserName undefined (type []models.User has no field or method UserName)

Upvotes: 1

Views: 3315

Answers (2)

Eklavya
Eklavya

Reputation: 18480

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

Upvotes: 2

mkopriva
mkopriva

Reputation: 38333

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

Upvotes: 1

Related Questions