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

标签 mysql go go-gorm go-gin

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

相关文章:

mysql - 不匹配的记录重定向到错误表?

Golang GORM 和几个表关联

go - 我怎样才能在 golang gorm 中与 self 建立多对多的关系?

mysql - 为什么这个 timestampdiff CASE 产生的 AVG 低于 WHEN 的值?

mysql - 使用 IPTABLES 限制 MySQL 3306 端口

mysql - 有效地更新用户配置文件

go - 如何阅读Cookie?

go - Go中的ForkExec和Su问题

testing - 如何使用 "testing"包在 Go 测试中打印?

json - 在 Go 中为导入的结构设置标签