hasmany same foreign key bug fixed and test added

This commit is contained in:
Paras 2021-05-17 23:57:17 +05:30
parent ad1c581de7
commit ecdec1d40c
2 changed files with 20 additions and 1 deletions

View File

@ -408,7 +408,7 @@ func (schema *Schema) guessRelation(relation *Relationship, field *Field, cgl gu
ff := foreignSchema.LookUpField(foreignKey) ff := foreignSchema.LookUpField(foreignKey)
pf := primarySchema.LookUpField(foreignKey) pf := primarySchema.LookUpField(foreignKey)
isKeySame := utils.ExistsIn(foreignKey, &relation.primaryKeys) isKeySame := utils.ExistsIn(foreignKey, &relation.primaryKeys)
if ff == nil || (pf != nil && ff != nil && schema == primarySchema && primarySchema != foreignSchema && !isKeySame) { if ff == nil || (pf != nil && ff != nil && schema == primarySchema && primarySchema != foreignSchema && !isKeySame && field.IndirectFieldType.Kind() == reflect.Struct) {
reguessOrErr() reguessOrErr()
return return
} else { } else {

View File

@ -501,3 +501,22 @@ func TestBelongsToWithSameForeignKey(t *testing.T) {
References: []Reference{{"ID", "Profile", "ProfileRefer", "User", "", false}}, References: []Reference{{"ID", "Profile", "ProfileRefer", "User", "", false}},
}) })
} }
func TestHasManySameForeignKey(t *testing.T) {
type Profile struct {
gorm.Model
Name string
UserRefer uint
}
type User struct {
gorm.Model
UserRefer uint
Profile []Profile `gorm:"ForeignKey:UserRefer"`
}
checkStructRelation(t, &User{}, Relation{
Name: "Profile", Type: schema.HasMany, Schema: "User", FieldSchema: "Profile",
References: []Reference{{"ID", "User", "UserRefer", "Profile", "", true}},
})
}