GORM嵌入式结构体无法正常工作。

huangapple go评论81阅读模式
英文:

GORM embedded struct not working correctly

问题

我收到了这个错误:

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)

User 模型的定义如下:

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 放在了与 User 相同的包中的不同文件中。迁移工作正常,因为 users 表中有 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

答案1

得分: 2

你在你的模型中使用了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)

huangapple
  • 本文由 发表于 2022年6月30日 23:57:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/72818776.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定