go-gorm - 如何在 GORM 中引用复合主键?
问题描述
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")
我怎样才能做到这一点?
解决方案
您可以使用ForeignKey
和References
标记。尽管在相反的(一对多)上下文中,但在文档中提到了它们。
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 `gorm:"ForeignKey:OrganizationID,UserName;References:OrganizationID,Name"`
}
AutoMigrate 将生成以下 sql:
CREATE TABLE `users` (`organization_id` integer NOT NULL,`name` text NOT NULL,PRIMARY KEY (`organization_id`,`name`))
CREATE TABLE `notes` (`id` integer NOT NULL,`organization_id` integer NOT NULL,`user_name` text NOT NULL,PRIMARY KEY (`id`),CONSTRAINT `fk_notes_user` FOREIGN KEY (`organization_id`,`user_name`) REFERENCES `users`(`organization_id`,`name`))
推荐阅读
- apache-nifi - Concat multiple columns with filter in QueryRecord (NiFi)
- ios - AudioToolbox ExtAudioFileSeek(_:_:) does not directly set the desired frame position
- java - 如何将 ArrayAdapter 参数应用为以编程方式制作的布局?
- django - Django 博客文章的计数器
- three.js - 在 Three.js 中在 3D 对象上渲染 Sprites,并且在没有剪辑的情况下在后面渲染
- c - 确定像素是否在安全范围内的有效方法
- sql - 查询只工作一个月的员工
- python - 有没有办法使海龟图形面向对象?
- mysql - 如何安排将 JSON 文件导入 MySQL Workbench?
- excel - 在数据透视表中显示数字后跟符号