GORM在"GORM.Model"未嵌入时惊慌失措



这是我的模型。请注意,我不想将gorm.Model嵌入到我的结构中。

type Order struct {
OrderID   uint64     `gorm:"column:order_id" gorm:"primaryKey" gorm:"unique"`
Cart      Cart       `gorm:"foreignKey:UserID"`
CreatedBy UserID     `gorm:"index"`
CreatedAt *time.Time `gorm:"autoCreateTime:nano"`
UpdatedAt *time.Time `gorm:"autoUpdateTime:nano"`
DeletedAt *time.Time
}
type Category struct {
ID        uint64     `gorm:"column:category_id" gorm:"primaryKey" gorm:"unique"`
Name      string     `gorm:"index"`
Image     string     
Products  []Product  `gorm:"foreignKey:product_id" gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
CreatedBy UserID     `gorm:"index" gorm:"type:bytea"`
CreatedAt *time.Time `gorm:"autoCreateTime:nano"`
UpdatedAt *time.Time `gorm:"autoUpdateTime:nano"`
DeletedAt *time.Time 
}
type Cart struct {
UserID    UserID     `gorm:"column:user_id" gorm:"primaryKey"`
Products  []Product  `gorm:"foreignKey:ID"`
Price     float64   
CreatedAt *time.Time `gorm:"autoCreateTime:nano"`
UpdatedAt *time.Time `gorm:"autoUpdateTime:nano"`
DeletedAt *time.Time 
}
type Product struct {
ID        uint64     `gorm:"column:product_id" gorm:"primaryKey" gorm:"unique"`
Name      string     `gorm:"index"`
Price     float64    `gorm:"index"`
Rating    uint       `gorm:"index"`
Image     string     
CreatedBy UserID     `gorm:"index" gorm:"type:bytea"`
CreatedAt *time.Time `gorm:"autoCreateTime:nano"`
UpdatedAt *time.Time `gorm:"autoUpdateTime:nano"`
DeletedAt *time.Time 
}

当我使用AutoMigrate时,我会得到以下错误:

[error] invalid field found for struct moonspace/model.Cart's field Products: define a valid foreign key for relations or implement the Valuer/Scanner interface

我已尝试将foreignKey:UserID更改为foreignKey:user_id,但错误保持不变。

这是我的自动迁移:

func createPostgresCLI(cfg types.Config, config ...any) *gorm.DB {
db, err := gorm.Open(postgres.Open(cfg.Url))
if err != nil {
panic(err)
}
err = db.AutoMigrate(&model.Order{}, &model.Cart{}, &model.Category{}, &model.Product{})
if err != nil {
panic(fmt.Errorf("Error creating database: %w", err))
}
return db
}

我做错了什么?此外,当我使用gorm.Model时,以及当我尝试将Product插入到Category中时,我会遇到外键约束错误。我正试图通过关联来添加它。

类别<=>产品:外键列需要包含在将引用类别ID的产品中。C当前配置在工作时会用类别ID更新产品ID,这将是错误的

type Category struct {
ID       uint64 `gorm:"column:category_id;primaryKey"`
Products  []Product  `gorm:"foreignKey:CategoryID" gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
....
}
type Product struct {
ID        uint64     `gorm:"column:product_id" gorm:"primaryKey" gorm:"unique"`
CategoryID uint64 // New field to hold category ID.
....
}

购物车<==>产品关系可以建模为许多具有连接表来存储产品和购物车ID的人,这里可能不需要外键。

type Cart struct {
CartID   uint64 `gorm:"primaryKey"`
Products []Product `gorm:"many2many:cart_products"`
....
}

此外您可以将所有gorm标记组合为一个,无需重复。

相关内容

  • 没有找到相关文章

最新更新