一切正常,但是当我清除数据库并再次启动应用程序时,出现此错误:
ERROR: relation "orders" does not exist (SQLSTATE 42P01)
我的代码:
type Cart struct {
gorm.Model
Products JSONB `gorm:"type:jsonb" json:"products"`
OrderID uint
}
type Jurik struct {
gorm.Model
Inn string `json:"inn" gorm:column:"inn"`
...
OrderID uint
}
type Phyz struct {
gorm.Model
Name string `json:"name" gorm:column:"name"`
...
OrderID uint
}
type Order struct {
gorm.Model
Cart Cart `json:"cart"`
User_id string `json:"user_id"`
Jurik Jurik `json:"jurik"`
Phyz Phyz `json:"phyz"`
}
我真的不明白可能出了什么问题,因为我的
Cart
Jurik
Phyz
表与Order
相关
我不知道它是如何工作的,但我之前的代码看起来像这样:
func Connect() {
db, err := gorm.Open(postgres.Open("postgres://postgres:qwerty@localhost:5432/shop"), &gorm.Config{})
if err != nil {
panic(err)
}
db.AutoMigrate(&models.Categories{}, &models.Products{}, &models.Pagination{}, &models.Feedback{}, &models.Cart{}, &models.Jurik{}, &models.Phyz{}, &models.Order{})
DB = db
}
然后我尝试为
Order
进行单独的迁移:
func Connect() {
db, err := gorm.Open(postgres.Open("postgres://postgres:qwerty@localhost:5432/shop"), &gorm.Config{})
if err != nil {
panic(err)
}
db.AutoMigrate(&models.Categories{}, &models.Products{}, &models.Pagination{}, &models.Feedback{}, &models.Cart{}, &models.Jurik{}, &models.Phyz{})
db.AutoMigrate(&models.Order{})
DB = db
}
希望这对某人有帮助!
我也有类似的错误,我必须通过gorm源代码来查看迁移是如何完成的。我注意到 gorm 根据约束依赖关系对模型进行排序和重新排序,这有时会导致依赖表在它们所依赖的表之前创建,从而导致错误。
“错误:关系不存在(SQLSTATE 42P01)”
建议的解决方案(但不是最好的)是首先创建具有依赖关系的表,然后创建依赖关系的表。