From e6f7da0e0dbc193df883f799a4650d0a86507376 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Fri, 18 Mar 2022 14:30:30 +0800 Subject: [PATCH] Support Variable Relation --- schema/relationship.go | 6 +++++- schema/relationship_test.go | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/schema/relationship.go b/schema/relationship.go index eae8ab0b..b5100897 100644 --- a/schema/relationship.go +++ b/schema/relationship.go @@ -416,6 +416,10 @@ func (schema *Schema) guessRelation(relation *Relationship, field *Field, cgl gu } } else { var primaryFields []*Field + var primarySchemaName = primarySchema.Name + if primarySchemaName == "" { + primarySchemaName = relation.FieldSchema.Name + } if len(relation.primaryKeys) > 0 { for _, primaryKey := range relation.primaryKeys { @@ -428,7 +432,7 @@ func (schema *Schema) guessRelation(relation *Relationship, field *Field, cgl gu } for _, primaryField := range primaryFields { - lookUpName := primarySchema.Name + primaryField.Name + lookUpName := primarySchemaName + primaryField.Name if gl == guessBelongs { lookUpName = field.Name + primaryField.Name } diff --git a/schema/relationship_test.go b/schema/relationship_test.go index 40ffc324..6fffbfcb 100644 --- a/schema/relationship_test.go +++ b/schema/relationship_test.go @@ -491,6 +491,26 @@ func TestEmbeddedRelation(t *testing.T) { } } +func TestVariableRelation(t *testing.T) { + var result struct { + User + } + + checkStructRelation(t, &result, Relation{ + Name: "Account", Type: schema.HasOne, Schema: "", FieldSchema: "Account", + References: []Reference{ + {"ID", "", "UserID", "Account", "", true}, + }, + }) + + checkStructRelation(t, &result, Relation{ + Name: "Company", Type: schema.BelongsTo, Schema: "", FieldSchema: "Company", + References: []Reference{ + {"ID", "Company", "CompanyID", "", "", false}, + }, + }) +} + func TestSameForeignKey(t *testing.T) { type UserAux struct { gorm.Model