From 8bf50a55927dbc74bd2168233f94dd957064bf8d Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Mon, 28 Dec 2020 17:58:12 +0800 Subject: [PATCH] Fix parse relations if only specfied References, close #3890 --- schema/relationship.go | 14 +++++++++++++- schema/relationship_test.go | 38 +++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/schema/relationship.go b/schema/relationship.go index 19945e0f..18f04e1f 100644 --- a/schema/relationship.go +++ b/schema/relationship.go @@ -396,7 +396,19 @@ func (schema *Schema) guessRelation(relation *Relationship, field *Field, gl gue } } } else { - for _, primaryField := range primarySchema.PrimaryFields { + var primaryFields []*Field + + if len(relation.primaryKeys) > 0 { + for _, primaryKey := range relation.primaryKeys { + if f := primarySchema.LookUpField(primaryKey); f != nil { + primaryFields = append(primaryFields, f) + } + } + } else { + primaryFields = primarySchema.PrimaryFields + } + + for _, primaryField := range primaryFields { lookUpName := primarySchema.Name + primaryField.Name if gl == guessBelongs { lookUpName = field.Name + primaryField.Name diff --git a/schema/relationship_test.go b/schema/relationship_test.go index 7d7fd9c9..af2897b8 100644 --- a/schema/relationship_test.go +++ b/schema/relationship_test.go @@ -55,6 +55,25 @@ func TestBelongsToOverrideReferences(t *testing.T) { }) } +func TestBelongsToWithOnlyReferences(t *testing.T) { + type Profile struct { + gorm.Model + Refer string + Name string + } + + type User struct { + gorm.Model + Profile Profile `gorm:"References:Refer"` + ProfileRefer int + } + + checkStructRelation(t, &User{}, Relation{ + Name: "Profile", Type: schema.BelongsTo, Schema: "User", FieldSchema: "Profile", + References: []Reference{{"Refer", "Profile", "ProfileRefer", "User", "", false}}, + }) +} + func TestSelfReferentialBelongsToOverrideReferences(t *testing.T) { type User struct { ID int32 `gorm:"primaryKey"` @@ -106,6 +125,25 @@ func TestHasOneOverrideReferences(t *testing.T) { }) } +func TestHasOneWithOnlyReferences(t *testing.T) { + type Profile struct { + gorm.Model + Name string + UserRefer uint + } + + type User struct { + gorm.Model + Refer string + Profile Profile `gorm:"References:Refer"` + } + + checkStructRelation(t, &User{}, Relation{ + Name: "Profile", Type: schema.HasOne, Schema: "User", FieldSchema: "Profile", + References: []Reference{{"Refer", "User", "UserRefer", "Profile", "", true}}, + }) +} + func TestHasManyOverrideForeignKey(t *testing.T) { type Profile struct { gorm.Model