GORM Playground Link
https://github.com/go-gorm/playground/pull/1
Description
The previous changes of @yushulgin haven't fixed the problem(#4343) or cause another issue. The similar bug mentioned in issue #4570 can be reproduced in the following way:
gorm version: gorm.io/gorm v1.21.12
Here is my codes:
type Goods struct {
Id uint `gorm:"primaryKey;autoIncrement;type:int" json:"id"`
Labels []GoodsLabel `gorm:"foreignKey:GoodsId;references:Id"` // hasMany
}
type GoodsLabel struct {
Id uint `gorm:"autoIncrement;primaryKey;type:int" json:"id"`
GoodsId int `gorm:"default:0;type:int;not null;comment:'Goods ID'" json:"goods_id"`
Goods Goods `gorm:"foreignKey:Id;references:GoodsId"` // hasOne
}
Relationship explanation: Each goods can has multiple labels, each label can only be attached to one goods. Goods has many GoodsLabel and GoodsLabel has one goods.
The above codes will cause an error "[error] invalid field found for struct xxx/models.GoodsLabel's field Goods: define a valid foreign key for relations or implement the Valuer/Scanner interface".
If I change the GoodsLabel struct to the following:
type GoodsLabel struct {
Id2 uint `gorm:"autoIncrement;primaryKey;type:int" json:"id"` // change "Id" field name to "Id2"
GoodsId int `gorm:"default:0;type:int;not null;comment:'Goods ID'" json:"goods_id"`
Goods Goods `gorm:"foreignKey:Id;references:GoodsId"` // hasOne
}
All codes will work well.
Comment From: github-actions[bot]
The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 2 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking ✨
Comment From: peterdeme
@athenakia managed to work around it?