我有以下结构
type datacenter struct {
Name string `gorm:"unique" json:"name"`
Datacenter_Id uuid.UUID `gorm:"type:uuid;primaryKey" json:"datacenter_id"`
Cluster_List []Cluster `gorm:"foreignKey:Datacenter_Id" json:"clusters"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
}
type Cluster struct {
Cluster_Id uuid.UUID `gorm:"type:uuid;primary_key;unique" json:"id"`
Num int `gorm:"unique" json:"num"`
Datacenter_Id uuid.UUID `json:"Datacenter_id"`
Servers_List []Server `gorm:"foreignKey:Cluster_Id" json:"servers"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index"`
}
type Server struct {
Scale_unit int `gorm:"unique" json:"scale_unit"`
Server_Id uuid.UUID `gorm:"type:uuid;primaryKey" json:"server_id"`
IP_Address string `json:"ip_address"`
Cluster_Id uuid.UUID `json:"cluster_id"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
}
我调用gorm automigrate代码在postgresql中创建表
if err := My_DB.AutoMigrate(&models.Datacenter{}); err != nil {
log.Fatalf("Error auto-migrating: %v", err)
}
if err := My_DB.AutoMigrate(&models.Cluster{}); err != nil {
log.Fatalf("Error auto-migrating: %v", err)
}
if err := My_DB.AutoMigrate(&models.Server{}); err != nil {
log.Fatalf("Error auto-migrating: %v", err)
}
型
但我一直得到下面的错误
2023/12/21 22:50:49 /app/database/db.go:116 ERROR: there is no unique constraint matching given keys for referenced table "datacenters" (SQLSTATE 42830)
[13.584ms] [rows:0] CREATE TABLE "clusters" ("cluster_id" uuid UNIQUE,"num" bigint UNIQUE,"datacenter_id" uuid,"created_at" timestamptz,"updated_at" timestamptz,"deleted_at" timestamptz,PRIMARY KEY ("cluster_id"),CONSTRAINT "fk_datacenters_clusters_list" FOREIGN KEY ("datacenter_id") REFERENCES "datacenters"("datacenter_id"))
2023/12/21 22:50:49 Error auto-migrating: ERROR: there is no unique constraint matching given keys for referenced table "datacenters" (SQLSTATE 42830)
型
我的想法是有一个数据中心结构,有一堆集群,每个集群包含许多服务器。我试图建立这种关系使用外键,我一直打与上述错误,我有“唯一”约束datacenter_id,但它仍然给我同样的错误。我该如何解决这个问题?
1条答案
按热度按时间cclgggtu1#
它被称为有很多关系,在Gorm有一个documentation
此外,我建议你按照naming conventions,如果你想Gorm工作的预期。
在此基础上,文档模型必须按照以下方式设计:
字符串