首页 > 解决方案 > 我可以在 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" )

这是我的错吗?

标签: gogo-gorm

解决方案


推荐阅读