我试图在两个数据库表之间创建一个属于的关系,使用GORM,我的代码如下:
type Shop struct {
ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid"`
Name string `json:"name" gorm:"not null" validate:"required"`
City string `json:"city" gorm:"not null" validate:"required"`
State string `json:"state" gorm:"not null" validate:"required"`
}type Employee struct {
ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid"`
FirstName string `json:"first_name" gorm:"not null" validate:"required"`
LastName string `json:"last_name" gorm:"not null" validate:"required"`
Email string `json:"email" gorm:"not null;unique" validate:"required,email"`
Password string `json:"password" gorm:"not null" validate:"required"`
Active bool `json:"active" gorm:"not null;default:false"`
ShopId uuid.UUID `json:"shop_id" gorm:"type:uuid"`
Shop Shop `gorm:"foreignKey:ShopID"`
}当我运行迁移时,会弹出以下错误:
[error] invalid field found for struct .../.../.../api/models.Employee's field Shop: define a valid foreign key for relations or implement the Valuer/Scanner interface我找到了一些使用数字主键的引用,它们似乎工作得很好,但是我找不到任何解决方法来处理uuid.
发布于 2022-05-04 19:22:19
我不确定,但我对消息错误的理解是,类型uuid.UUID没有为Valuer和Scanner接口实现方法。
您应该创建自己的UUID类型,它可以如下所示:
type UUID uuid.UUID
func(id UUID) Value() (driver.Value, error) {
return id.String(), nil
}
func (id *UUID) Scan(value interface{}) error {
dbID, ok := value.(string)
if !ok {
return errors.New("id scan: invalid value")
}
*e = uuid.MustParse(dbID)
return nil
}并将其用于结构的定义:
type Shop struct {
ID UUID `json:"id" gorm:"primaryKey;type:uuid"`
//...
}https://stackoverflow.com/questions/72117428
复制相似问题