Gorm 外键

问题描述 投票:0回答:1

有人知道为什么这段代码不起作用以及如何解决它吗?

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.AutoMigrate(&model.AccountCredentials{}, &model.AccountVerification{}, &model.User{})

我收到以下错误:

在 struct pkg/model 中发现无效字段。用户字段 AccountCredentials:为关系定义有效的外键或实现 Valuer/Scanner 接口

go foreign-keys go-gorm
1个回答
0
投票

拼写错误是使用

,
代替
;
,也使用
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"`
}
© www.soinside.com 2019 - 2024. All rights reserved.