GORM嵌入结构无法正常工作

发布于 2025-02-11 18:53:18 字数 794 浏览 2 评论 0原文

时,我会收到此错误

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

好久不见√ 2025-02-18 18:53:18

您已经使用basemodel作为模型中的属性,因此,即使Gorm可以很好地将其映射到表列以访问它,您必须使用属性名称

以访问您,

jwtToken, err := generateJWT(user.BaseModel.ID, user.Username)

您也可以尝试此操作。 代码以查看是否有效

type BaseModel struct {
    ID        uint `json:"id" gorm:"primaryKey"`
    CreatedAt time.Time
    UpdatedAt time.Time
}

type User struct {
    BaseModel `gorm:"embedded"`
    Username  string    `json:"username"`
    Password  string    `json:"password"`
}

下一个

jwtToken, err := generateJWT(user.ID, user.Username)

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 name

To access you would do

jwtToken, err := generateJWT(user.BaseModel.ID, user.Username)

you could also try this next code to see if it works otherwise the above will work for sure

type BaseModel struct {
    ID        uint `json:"id" gorm:"primaryKey"`
    CreatedAt time.Time
    UpdatedAt time.Time
}

type User struct {
    BaseModel `gorm:"embedded"`
    Username  string    `json:"username"`
    Password  string    `json:"password"`
}

now you might be able to access it like your original pattern

jwtToken, err := generateJWT(user.ID, user.Username)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文