Support Variable Relation

This commit is contained in:
Jinzhu 2022-03-18 14:30:30 +08:00
parent 5431da8caf
commit e6f7da0e0d
2 changed files with 25 additions and 1 deletions

View File

@ -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
}

View File

@ -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