我正在尝试使用 https://github.com/jinzhu/gorm自动为我映射外键,但不知何故,要么我做错了,要么图书馆做不到,我错了。
我有以下结构
:
type Currency struct {
ID uint64 `gorm:"primary_key"`
CurrencyCode string `gorm:"size:3"`
}
type Rate struct {
ID uint64 `gorm:"primary_key"`
CurrencyID uint64
Currency Currency `gorm:"ForeignKey:CurrencyID"`
Price float64
}
和以下 SQL 表(经过编辑以便 currency_code 是唯一的)
CREATE TABLE `rates` (
`id` serial PRIMARY KEY,
`currency_id` bigint unsigned NOT NULL,
`price` decimal(12,2) NOT NULL,
CONSTRAINT `fk_rate_currency`
FOREIGN KEY (currency_id) REFERENCES currencies(id)
);
CREATE TABLE `currencies` (
`id` serial PRIMARY KEY,
`currency_code` char(3) NOT NULL UNIQUE
);
现在我想当我做这样的事情时:
rate := Rate{
Currency: Currency{
CurrencyCode: "USD",
},
Price: 123,
}
db, _ := gorm.Open("mysql", ...)
db.Create(&rate)
然后 "USD"
将自动映射到 currency_id
但它会在 currencies< 中插入新的
每个 "USD"
条目db.Create(&rate)
是我做错了还是图书馆的问题?
编辑
我知道我可以通过在数据库中查询货币 ID 来做到这一点
curr := db.Currency{}
db.Where("currency_code = ?", "USD").First(&curr)
// use curr with proper ID
然后:
- 我必须进行 2 次数据库调用
- 我不使用
gorm
的外键映射功能(如果有的话)
最佳答案
在他们的 documentation它指出:
By default when creating/updating a record, GORM will save its associations, if the association has primary key, GORM will call Update to save it, otherwise it will be created.
所以当你想映射到某个条目时,你必须将它与ID相关联,否则它会创建一个新记录。
在您的情况下,您可以使用 currency_code
作为 Currency
的 PRIMARY KEY(使用固定数量的字符使其更快,而不是varchar,如 sql:"type:char(3);unique"
)。
这将不再需要按 ID 进行搜索,它只会找到“USD”作为主键并使用它 => 每个货币不再有多个记录。此外,如果存在它没有的货币,它会在 Currency
表中创建它。
您还可以删除 gorm:"ForeignKey:CurrencyID"
结构标记,让 GORM 使用 AutoMigrate 创建自己的表, 并将创建具有适当 FK 的表:
db := gorm.Open("mysql", ...)
db.Set("gorm:table_options", "ENGINE=InnoDB")
db.Set("gorm:table_options", "collation_connection=utf8_general_ci")
// Migrate the schema
db.AutoMigrate(&models.Currency{})
db.AutoMigrate(&models.Rate{})
关于mysql - gorm.DB 可以自动解析外键吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48311125/