Skip to content

Commit

Permalink
fixed has_many stopped working if field names are identical (go-gorm#…
Browse files Browse the repository at this point in the history
…4387)

* fixed belongs_to & has_one reversed if field same

* hasmany same foreign key bug fixed and test added
  • Loading branch information
paraswaykole authored May 19, 2021
1 parent cf93b16 commit 79f427d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
2 changes: 1 addition & 1 deletion schema/relationship.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
19 changes: 19 additions & 0 deletions schema/relationship_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}},
})
}

0 comments on commit 79f427d

Please sign in to comment.