go - 我可以在 Gorm 中以这种方式使用复合主键吗?为什么 SQLSTATE 42830 错误?
问题描述
我需要使用复合主键创建这些表:
type Tenant struct {
gorm.Model
Description string
}
type BaseModel struct {
gorm.Model
TenantID uint `gorm:"primaryKey"`
Tenant Tenant
}
type Player struct {
BaseModel
Name string
Teams []Team
}
type Team struct {
BaseModel
Name string
PlayerID uint
}
但如果我使用:
myDB.AutoMigrate(
&Tenant{},
&Player{},
&Team{},
)
它抛出:
C:/go/pkg/mod/gorm.io/driver/postgres@v1.1.0/migrator.go:157 ERROR: there is no unique constraint matching given keys for referenced table "players" (SQLSTATE 42830)
[15.960ms] [rows:0] CREATE TABLE "teams" ("id" bigserial,"created_at" timestamptz,"updated_at" timestamptz,"deleted_at" timestamptz,"tenant_id" bigint,"name" text,"player_id" bigint,PRIMARY KEY ("id","tenant_id"),CONSTRAINT "fk_teams_tenant" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id"),CONSTRAINT "fk_players_teams" FOREIGN KEY ("player_id") REFERENCES "players"("id"))
panic: ERROR: there is no unique constraint matching given keys for referenced table "players" (SQLSTATE 42830)
Tenant
如果我从中删除BaseModel
它有效。
我可以用Composite Primary Key
这种方式吗?
你能告诉我为什么它不起作用吗?
更新:
它产生的问题是:
CREATE TABLE "teams" (
"id" bigserial,
"created_at" timestamptz,
"updated_at" timestamptz,
"deleted_at" timestamptz,
"tenant_id" BIGINT,
"name" TEXT,
"player_id" BIGINT NOT NULL,
PRIMARY KEY ( "id", "tenant_id" ),
CONSTRAINT "fk_teams_tenant" FOREIGN KEY ( "tenant_id" ) REFERENCES "tenants" ( "id" ),
CONSTRAINT "fk_players_teams" FOREIGN KEY ("player_id") REFERENCES "players"("id")
)
代替:
CREATE TABLE "teams" (
"id" bigserial,
"created_at" timestamptz,
"updated_at" timestamptz,
"deleted_at" timestamptz,
"tenant_id" BIGINT,
"name" TEXT,
"player_id" BIGINT NOT NULL,
PRIMARY KEY ( "id", "tenant_id" ),
CONSTRAINT "fk_teams_tenant" FOREIGN KEY ( "tenant_id" ) REFERENCES "tenants" ( "id" ),
CONSTRAINT "fk_players_teams" FOREIGN KEY ( "player_id", "tenant_id" ) REFERENCES "players" ( "id", "tenant_id" )
)
这是区别:
- CONSTRAINT "fk_players_teams" FOREIGN KEY ("player_id") REFERENCES "players"("id")
+ CONSTRAINT "fk_players_teams" FOREIGN KEY ( "player_id", "tenant_id" ) REFERENCES "players" ( "id", "tenant_id" )
这是我的错吗?
解决方案
推荐阅读
- javascript - 访问有关在 indexedDB 中导致请求出错的数据对象的信息
- php - 如何在mysql中水平显示生物识别设备的进出时间?
- javascript - 用于在 React 组件中填充下拉列表的多个 API 调用
- json - 正则表达式过滤 json 值
- azure - Azure 中的服务 ID 是什么?
- android - 更改活动时保持线程处于活动状态
- javascript - Json 数据的字符串名称有“-”
- jquery - clearTimeout() 在 jquery 中不起作用
- docker-compose - 如何禁用翻译弹出式chrome
- python - python pygame 使用 spyder