From 79f427d8625842abeb24debceb7249223ae86d82 Mon Sep 17 00:00:00 2001 From: Paras Waykole Date: Wed, 19 May 2021 13:35:29 +0530 Subject: [PATCH] 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 --- schema/relationship.go | 2 +- schema/relationship_test.go | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/schema/relationship.go b/schema/relationship.go index b2d485de..62256c28 100644 --- a/schema/relationship.go +++ b/schema/relationship.go @@ -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 { diff --git a/schema/relationship_test.go b/schema/relationship_test.go index 391e3a25..d0ffc28a 100644 --- a/schema/relationship_test.go +++ b/schema/relationship_test.go @@ -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}}, + }) +}