fixed has_many stopped working if field names are identical (#4387)

* fixed belongs_to & has_one reversed if field same

* hasmany same foreign key bug fixed and test added
This commit is contained in:
Paras Waykole 2021-05-19 13:35:29 +05:30 committed by GitHub
parent cf93b16730
commit 79f427d862
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 1 deletions

View File

@ -408,7 +408,7 @@ func (schema *Schema) guessRelation(relation *Relationship, field *Field, cgl gu
ff := foreignSchema.LookUpField(foreignKey)
pf := primarySchema.LookUpField(foreignKey)
isKeySame := utils.ExistsIn(foreignKey, &relation.primaryKeys)
if ff == nil || (pf != nil && ff != nil && schema == primarySchema && primarySchema != foreignSchema && !isKeySame) {
if ff == nil || (pf != nil && ff != nil && schema == primarySchema && primarySchema != foreignSchema && !isKeySame && field.IndirectFieldType.Kind() == reflect.Struct) {
reguessOrErr()
return
} else {

View File

@ -501,3 +501,22 @@ func TestBelongsToWithSameForeignKey(t *testing.T) {
References: []Reference{{"ID", "Profile", "ProfileRefer", "User", "", false}},
})
}
func TestHasManySameForeignKey(t *testing.T) {
type Profile struct {
gorm.Model
Name string
UserRefer uint
}
type User struct {
gorm.Model
UserRefer uint
Profile []Profile `gorm:"ForeignKey:UserRefer"`
}
checkStructRelation(t, &User{}, Relation{
Name: "Profile", Type: schema.HasMany, Schema: "User", FieldSchema: "Profile",
References: []Reference{{"ID", "User", "UserRefer", "Profile", "", true}},
})
}