在做gorm 查询时能正常返回记录但有的字段始终取不到值,
模型定义如下:
模型首字母必须大写
type User struct {
ID uint32 `gorm:"primary_key" json:"id"`
UserName string `json:"username"`
PassWord string `json:"password"`
LoginTime int `json:"logintime"`
Status uint8 `json:"status"`
}
执行的sql: SELECT * FROM `ly_user` WHERE (username = 'admin') ORDER BY `ly_user`.`id` ASC LIMIT 1
返回结果:
user={ID:1 UserName: PassWord: LoginTime:0 Status:1}
user = {1 0 1}
获取不到 UserName, PassWord, LoginTime 这三个字段值
分析:没有遵循gorm 默认的模型列名命名规则
规则如下:
根据约定,数据表的列名使用的是 struct 字段名的 蛇形命名
type User struct {
ID uint // 列名是 `id`
Name string // 列名是 `name`
Birthday time.Time // 列名是 `birthday`
CreatedAt time.Time // 列名是 `created_at`
}
根据命名规则可以做如下修改
1、
type User struct {
ID uint32 `gorm:"primary_key" json:"id"`
UserName string `json:"username" gorm:"column:username"`
PassWord string `json:"password" gorm:"column:password"`
LoginTime int `json:"logintime" gorm:"column:logintime"`
Status uint8 `json:"status"`
}
2、
type User struct {
ID uint32 `gorm:"primary_key" json:"id"`
Username string `json:"username"`
Password string `json:"password"`
Logintime int `json:"logintime"`
Status uint8 `json:"status"`
}
3、如果你要用上面第一种那么你就要修改表的列名 修改为UserName 对应列修改为 user_name,
PassWord 修改为pass_word, LoginTime 修改为 login_time