GORM嵌入结构无法正常工作
时,我会收到此错误
controllers/users.go:61:36: user.ID undefined (type models.User has no field or method ID)
当使用
var user models.User
...
jwtToken, err := generateJWT(user.ID, user.Username)
用户
模型的定义
package models
import "time"
type BaseModel struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
}
type User struct {
BaseModel BaseModel `gorm:"embedded"`
Username string `json:"username"`
Password string `json:"password"`
}
:实际上,我将basemodel
放在不同的文件中,但使用用户
中的同一软件包。迁移工作正常,作为表用户
在basemodel
中都有所有列。问题是什么?我使用Golang
1.18和最新版本的gorm
I receive this error
controllers/users.go:61:36: user.ID undefined (type models.User has no field or method ID)
when using
var user models.User
...
jwtToken, err := generateJWT(user.ID, user.Username)
The definition of User
model:
package models
import "time"
type BaseModel struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
}
type User struct {
BaseModel BaseModel `gorm:"embedded"`
Username string `json:"username"`
Password string `json:"password"`
}
Actually I put BaseModel
in different file but in the same package with User
. Migration works fine as table users
have all columns in BaseModel
. What is the problem? I use golang
1.18 and latest version of GORM
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您已经使用
basemodel
作为模型中的属性,因此,即使Gorm可以很好地将其映射到表列以访问它,您必须使用属性名称以访问您,
您也可以尝试此操作。 代码以查看是否有效
下一个
You have used
BaseModel
as attribute in your model so even though gorm can very well map it to the table column to access it, you have to use the attribute nameTo access you would do
you could also try this next code to see if it works otherwise the above will work for sure
now you might be able to access it like your original pattern