playground
playground copied to clipboard
wrong foreignKey setup for multiple ebedded belongs-to relations
Explain your user case and expected results
When using multiple embedded belongs-to relations only 1 database foreignKey is created. Expected: a foreignKey for each relation is created.
type Country struct {
Name string `gorm:"primaryKey"`
}
type Address struct {
CountryName string
Country Country
}
type Org struct {
ID int
Address1 Address `gorm:"embedded;embeddedPrefix:address1_"`
Address2 Address `gorm:"embedded;embeddedPrefix:address2_"`
}
In the above example there should be a foreignKey for address1 -> countries and a foreignKey address2 -> countries.
gorm only creates one foreignKey fk_orgs_country
=> address2_country_name->countries
Hint:
- the generated naming for the foreignKey should respect the fieldName with its path / parent struct, as both relations result in the same foreignKey name.
- the relations are correctly detected as embedded and belongs-to, but result in only one entry in the relations map, this is due to the fact that only fieldName is used within this map
- possible solution: consider using BindNames of the field for name generation