Skip to content

Wrong foreignKey setup for multiple embedded belongs-to relations of same type #6751

Open
@cstaud

Description

@cstaud

GORM Playground Link

go-gorm/playground#672

Description

cnp from the playground PR

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions