这是我的模型。请注意,我不想将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中时,我会得到一个外键约束错误。我正试图通过联想来添加它。
发布于 2022-10-31 05:03:16
类别<==>产品:产品中需要包含外键列,该列将引用类别ID。在工作时,CUrrent配置将使用类别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.
....
}Cart <===> products关系可以建模为带有连接表的many2many,以存储产品和手推车的ID,这里可能不需要外键。
type Cart struct {
CartID uint64 `gorm:"primaryKey"`
Products []Product `gorm:"many2many:cart_products"`
....
}还可以使用将所有gorm标记合并为一个,不需要重复。
https://stackoverflow.com/questions/74257010
复制相似问题