I'm trying to use https://github.com/jinzhu/gorm to automatically map foreign keys for me but somehow either I'm doing it wrong or the library cannot do it and I'm in the wrong.
I have the following struct
s:
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
}
and the following SQL tables (edited so that currency_code is unique)
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
);
Now I thought that when I do something like this:
rate := Rate{
Currency: Currency{
CurrencyCode: "USD",
},
Price: 123,
}
db, _ := gorm.Open("mysql", ...)
db.Create(&rate)
then "USD"
would get automatically mapped to a currency_id
but instead it inserts new "USD"
entry in currencies
table for every db.Create(&rate)
Am I doing it wrong or it's the library?
EDIT
I know that I can do it by querying the DB for currency ID
curr := db.Currency{}
db.Where("currency_code = ?", "USD").First(&curr)
// use curr with proper ID
but then:
- I have to make 2 DB calls
- I don't use
gorm
's foreign key mapping feature (if there is one)