有谁知道为什么这个代码不能工作,以及如何解决它?

type Model struct {
    ID        uuid.UUID `gorm:"type:uuid;primary_key;"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time `sql:"index"`
}

func (model *Model) BeforeCreate(tx *gorm.DB) (err error) {
    model.ID = uuid.New()
    return
}

type User struct {
    Model
    Name                string
    Email               string `gorm:"primaryKey"`
    Description         string
    AccountCredentials  AccountCredentials  `gorm:"foreignKey:Email,constraint:OnUpdate:CASCADE,onDelete:CASCADE"`
    AccountVerification AccountVerification `gorm:"foreignKey:Email,constraint:OnUpdate:CASCADE,onDelete:CASCADE"`
}

type AccountCredentials struct {
    Email    string `gorm:"primaryKey"`
    Password string
}

type AccountVerification struct {
    Email               string `gorm:"primaryKey"`
    VerificationCode    string
    VerificationCodeTTL int64
    IsVerified          bool
    CreatedAt           time.Time `gorm:"autoCreateTime:true"`
}

当我自动迁移DB时:

    db.AutoMigrate(&model.AccountCredentials{}, &model.AccountVerification{}, &model.User{})

我收到以下错误:

为struct pkg/Model找到无效的字段.用户的字段Account Credentials:为关系定义有效的外键或实现Valuer/Scanner接口

推荐答案

错别字是用,代替;,也用references:

type Model struct {
    ID        uuid.UUID `gorm:"type:uuid;primary_key;"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time `sql:"index"`
}

func (model *Model) BeforeCreate(tx *gorm.DB) (err error) {
    model.ID = uuid.New()
    return
}

type User struct {
    Model
    Name                string
    Email               string `gorm:"primaryKey"`
    Description         string
    AccountCredentials  AccountCredentials  `gorm:"foreignKey:Email;references:Email;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
    AccountVerification AccountVerification `gorm:"foreignKey:Email;references:Email;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
}

type AccountCredentials struct {
    Email    string `gorm:"primaryKey"`
    Password string
}

type AccountVerification struct {
    Email               string `gorm:"primaryKey"`
    VerificationCode    string
    VerificationCodeTTL int64
    IsVerified          bool
    CreatedAt           time.Time `gorm:"autoCreateTime:true"`
}

Go相关问答推荐

Go 1.22 http mux:在同一路径上提供一个手柄和一个FS

mockgen不创建模拟

允许在 struct 中使用复合作为函数参数

如何在Golang中使用ECHO服务器实现Socket.IO服务器

在 Go 中解组编号的 XML 标签

Golang - POST 失败(NoSurf CSRF)

类型/ struct 函数的 GoDoc 示例函数

如何在 Golang http.Request 对象中读取自定义 ajaxParams

如何使用 Go 代理状态为 OK 的预检请求?

CBC Decrypter 解密加密文本,但部分文本被随机字符替换

为什么 `append(x[:0:0], x...)` 将切片复制到 Go 中的新后备数组中?

获取切片元素的地址是否意味着 Go 中元素的副本?

速率限制特定端点

不能在 *gorm.db 而不是 gorm.db 上使用 WithContext(ctx) 方法

将 .gz 文件添加到 tar.gz 文件,但在添加之前解码 gz.输出文件被剪辑(损坏)

有没有办法将 yaml node 添加到 golang 中现有的 yaml 文档中?

有没有办法判断值是否满足接口中定义的类型约束?

使用 oklog/run 来自 Go 编译器的错误(无值)用作值

如何获取多个 url 参数值

获取单调时间,同 CLOCK_MONOTONIC