【发布时间】:2020-09-03 14:51:22
【问题描述】:
Golang 的 GORM 库支持复合主键。但是如何从相关模型中引用它们呢?
例如,假设我有一个 User 和一个 Note 模型:
type User struct {
OrganizationID uint `gorm:"primaryKey; not null"`
Name string `gorm:"primaryKey; not null"`
}
type Note struct {
ID uint `gorm:"primaryKey; not null"`
OrganizationID uint `gorm:"not null"`
UserName string `gorm:"not null"`
User User
}
自动迁移器像这样创建notes 表,但失败:
CREATE TABLE "notes" ("id" bigserial NOT NULL,"user_name" text NOT NULL,"organization_id" bigint NOT NULL,PRIMARY KEY ("id"),
CONSTRAINT "fk_notes_user" FOREIGN KEY ("user_name") REFERENCES "users"("name"))
但我希望它这样做:
CONSTRAINT "fk_notes_user" FOREIGN KEY ("user_name", "organization_id") REFERENCES "users"("name", "organization_id")
我怎样才能做到这一点?
【问题讨论】:
标签: go-gorm