简体   繁体   English

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

[英]Get Selected value from Golang Gorm Query

I want to get user data after I do query using gorm我想在使用 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?我只想在从gorm查询后获取用户名,如何获取? I'm using item.Username but, the error show that item.UserName undefined (type []models.User has no field or method UserName)我正在使用item.Username但错误显示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] ). []表示一个slice ,这意味着item不是单个用户而是一个用户切片,并且 slice 没有字段,它们具有存储在其中的单个实例的元素,要访问这些元素,您可以使用索引表达式( s[i] )。 Either do item[0].UserName or declare item as a single user, not a slice.要么做item[0].UserName要么将item声明为单个用户,而不是切片。 ie item:= model.User{} then you can use the selector expression item.UserName .item:= model.User{}那么你可以使用选择器表达式item.UserName

You are trying to get UserName from slice of user that the problem.您正在尝试从存在问题的用户切片中获取UserName If email is a unique field database then you can use the user model only rather using slice of user.如果 email 是唯一字段数据库,那么您可以仅使用用户 model 而不是使用用户切片。

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

Then you can access like username like item.UserName然后你可以像item.UserName这样的用户名访问

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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