From 8f7f3ad3153c2bbcd6a74f6758ac819260ad7189 Mon Sep 17 00:00:00 2001 From: Paras Waykole Date: Wed, 5 May 2021 05:27:54 +0530 Subject: [PATCH] fixed belongs_to & has_one reversed if field same (#4343) --- schema/relationship.go | 10 +++++++--- schema/relationship_test.go | 19 +++++++++++++++++++ utils/utils.go | 12 ++++++++++++ 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/schema/relationship.go b/schema/relationship.go index fee96cbd..b2d485de 100644 --- a/schema/relationship.go +++ b/schema/relationship.go @@ -7,6 +7,7 @@ import ( "github.com/jinzhu/inflection" "gorm.io/gorm/clause" + "gorm.io/gorm/utils" ) // RelationshipType relationship type @@ -404,11 +405,14 @@ func (schema *Schema) guessRelation(relation *Relationship, field *Field, cgl gu if len(relation.foreignKeys) > 0 { for _, foreignKey := range relation.foreignKeys { - if f := foreignSchema.LookUpField(foreignKey); f != nil { - foreignFields = append(foreignFields, f) - } else { + 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) { reguessOrErr() return + } else { + foreignFields = append(foreignFields, ff) } } } else { diff --git a/schema/relationship_test.go b/schema/relationship_test.go index 2971698c..391e3a25 100644 --- a/schema/relationship_test.go +++ b/schema/relationship_test.go @@ -482,3 +482,22 @@ func TestSameForeignKey(t *testing.T) { }, ) } + +func TestBelongsToWithSameForeignKey(t *testing.T) { + type Profile struct { + gorm.Model + Name string + ProfileRefer int + } + + type User struct { + gorm.Model + Profile Profile `gorm:"ForeignKey:ProfileRefer"` + ProfileRefer int + } + + checkStructRelation(t, &User{}, Relation{ + Name: "Profile", Type: schema.BelongsTo, Schema: "User", FieldSchema: "Profile", + References: []Reference{{"ID", "Profile", "ProfileRefer", "User", "", false}}, + }) +} diff --git a/utils/utils.go b/utils/utils.go index ecba7fb9..ce6f35df 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -111,3 +111,15 @@ func ToString(value interface{}) string { } return "" } + +func ExistsIn(a string, list *[]string) bool { + if list == nil { + return false + } + for _, b := range *list { + if b == a { + return true + } + } + return false +}