mirror of https://github.com/go-gorm/gorm.git
fixed belongs_to & has_one reversed if field same (#4343)
This commit is contained in:
parent
70e93e73d8
commit
8f7f3ad315
|
@ -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 {
|
||||||
|
|
|
@ -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}},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
|
@ -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
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue