mirror of https://github.com/go-gorm/gorm.git
Fix parse relations if only specfied References, close #3890
This commit is contained in:
parent
ade0bd6d60
commit
8bf50a5592
|
@ -396,7 +396,19 @@ func (schema *Schema) guessRelation(relation *Relationship, field *Field, gl gue
|
|||
}
|
||||
}
|
||||
} else {
|
||||
for _, primaryField := range primarySchema.PrimaryFields {
|
||||
var primaryFields []*Field
|
||||
|
||||
if len(relation.primaryKeys) > 0 {
|
||||
for _, primaryKey := range relation.primaryKeys {
|
||||
if f := primarySchema.LookUpField(primaryKey); f != nil {
|
||||
primaryFields = append(primaryFields, f)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
primaryFields = primarySchema.PrimaryFields
|
||||
}
|
||||
|
||||
for _, primaryField := range primaryFields {
|
||||
lookUpName := primarySchema.Name + primaryField.Name
|
||||
if gl == guessBelongs {
|
||||
lookUpName = field.Name + primaryField.Name
|
||||
|
|
|
@ -55,6 +55,25 @@ func TestBelongsToOverrideReferences(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
func TestBelongsToWithOnlyReferences(t *testing.T) {
|
||||
type Profile struct {
|
||||
gorm.Model
|
||||
Refer string
|
||||
Name string
|
||||
}
|
||||
|
||||
type User struct {
|
||||
gorm.Model
|
||||
Profile Profile `gorm:"References:Refer"`
|
||||
ProfileRefer int
|
||||
}
|
||||
|
||||
checkStructRelation(t, &User{}, Relation{
|
||||
Name: "Profile", Type: schema.BelongsTo, Schema: "User", FieldSchema: "Profile",
|
||||
References: []Reference{{"Refer", "Profile", "ProfileRefer", "User", "", false}},
|
||||
})
|
||||
}
|
||||
|
||||
func TestSelfReferentialBelongsToOverrideReferences(t *testing.T) {
|
||||
type User struct {
|
||||
ID int32 `gorm:"primaryKey"`
|
||||
|
@ -106,6 +125,25 @@ func TestHasOneOverrideReferences(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
func TestHasOneWithOnlyReferences(t *testing.T) {
|
||||
type Profile struct {
|
||||
gorm.Model
|
||||
Name string
|
||||
UserRefer uint
|
||||
}
|
||||
|
||||
type User struct {
|
||||
gorm.Model
|
||||
Refer string
|
||||
Profile Profile `gorm:"References:Refer"`
|
||||
}
|
||||
|
||||
checkStructRelation(t, &User{}, Relation{
|
||||
Name: "Profile", Type: schema.HasOne, Schema: "User", FieldSchema: "Profile",
|
||||
References: []Reference{{"Refer", "User", "UserRefer", "Profile", "", true}},
|
||||
})
|
||||
}
|
||||
|
||||
func TestHasManyOverrideForeignKey(t *testing.T) {
|
||||
type Profile struct {
|
||||
gorm.Model
|
||||
|
|
Loading…
Reference in New Issue