Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Inferred foreign key depends on whether the type is exported or not #3928

@martinxsliu

Description

@martinxsliu

GORM Playground Link

go-gorm/playground#246

Description

I would like to report a regression (from v1) that the inferred foreign key field name are now dependent on whether the referenced type is exported or not. This was not the case in v1 and I ran into this when attempting to upgrade to v2. I couldn't find any mentions of this here), so I'm not sure if this was an intentional change or not.

If you don't explicitly set a foreign key field using the gorm:"foreignKey:foo" tag, then gorm will attempt to infer the foreign key field by using the referenced type name plus its primary field name.

type User struct {
	gorm.Model
	Name      string
	Age       uint
	Birthday  *time.Time
	Account   Account
}

type Account struct {
	gorm.Model
	UserID sql.NullInt64
	Number string
}

In the playground example (shown above), the referenced type name is User and its pk field name is ID so the foreign key field will be successfully inferred as UserID.

However, if you change the User type to be not exported, i.e. user, then this fails with the error:

invalid field found for struct gorm.io/playground.user's field Account, need to define a valid foreign key for relations or it need to implement the Valuer/Scanner interface

This error goes away if you explicitly add a foreign key tag though, e.g.

type user struct {
	gorm.Model
	Name      string
	Age       uint
	Birthday  *time.Time
	Account   Account `gorm:"foreignKey:UserID"`
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions