fixed belongs_to & has_one reversed if field same (#4343)

This commit is contained in:
Paras Waykole 2021-05-05 05:27:54 +05:30 committed by GitHub
parent 70e93e73d8
commit 8f7f3ad315
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 38 additions and 3 deletions

View File

@ -7,6 +7,7 @@ import (
"github.com/jinzhu/inflection" "github.com/jinzhu/inflection"
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
"gorm.io/gorm/utils"
) )
// RelationshipType relationship type // RelationshipType relationship type
@ -404,11 +405,14 @@ func (schema *Schema) guessRelation(relation *Relationship, field *Field, cgl gu
if len(relation.foreignKeys) > 0 { if len(relation.foreignKeys) > 0 {
for _, foreignKey := range relation.foreignKeys { for _, foreignKey := range relation.foreignKeys {
if f := foreignSchema.LookUpField(foreignKey); f != nil { ff := foreignSchema.LookUpField(foreignKey)
foreignFields = append(foreignFields, f) pf := primarySchema.LookUpField(foreignKey)
} else { isKeySame := utils.ExistsIn(foreignKey, &relation.primaryKeys)
if ff == nil || (pf != nil && ff != nil && schema == primarySchema && primarySchema != foreignSchema && !isKeySame) {
reguessOrErr() reguessOrErr()
return return
} else {
foreignFields = append(foreignFields, ff)
} }
} }
} else { } else {

View File

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

View File

@ -111,3 +111,15 @@ func ToString(value interface{}) string {
} }
return "" return ""
} }
func ExistsIn(a string, list *[]string) bool {
if list == nil {
return false
}
for _, b := range *list {
if b == a {
return true
}
}
return false
}