Search code examples
goforeign-keysgo-gorm

Gorm Foreign Keys


Anyone knows why this code is not working and how to solve it?

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"`
}

When I'm automigrating the DB:

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

I'm receiving the following errors:

invalid field found for struct pkg/model.User's field AccountCredentials: define a valid foreign key for relations or implement the Valuer/Scanner interface


Solution

  • The typo is in using , instead of ;, also use the 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"`
    }