diff --git a/schema/relationship.go b/schema/relationship.go index 18f04e1f..4580fa53 100644 --- a/schema/relationship.go +++ b/schema/relationship.go @@ -414,9 +414,18 @@ func (schema *Schema) guessRelation(relation *Relationship, field *Field, gl gue lookUpName = field.Name + primaryField.Name } - if f := foreignSchema.LookUpField(lookUpName); f != nil { - foreignFields = append(foreignFields, f) - primaryFields = append(primaryFields, primaryField) + lookUpNames := []string{lookUpName} + if len(primaryFields) == 1 { + lookUpNames = append(lookUpNames, strings.TrimSuffix(lookUpName, primaryField.Name)+"ID") + lookUpNames = append(lookUpNames, strings.TrimSuffix(lookUpName, primaryField.Name)+"Id") + } + + for _, name := range lookUpNames { + if f := foreignSchema.LookUpField(name); f != nil { + foreignFields = append(foreignFields, f) + primaryFields = append(primaryFields, primaryField) + break + } } } } diff --git a/schema/relationship_test.go b/schema/relationship_test.go index af2897b8..887e1341 100644 --- a/schema/relationship_test.go +++ b/schema/relationship_test.go @@ -74,6 +74,25 @@ func TestBelongsToWithOnlyReferences(t *testing.T) { }) } +func TestBelongsToWithOnlyReferences2(t *testing.T) { + type Profile struct { + gorm.Model + Refer string + Name string + } + + type User struct { + gorm.Model + Profile Profile `gorm:"References:Refer"` + ProfileID int + } + + checkStructRelation(t, &User{}, Relation{ + Name: "Profile", Type: schema.BelongsTo, Schema: "User", FieldSchema: "Profile", + References: []Reference{{"Refer", "Profile", "ProfileID", "User", "", false}}, + }) +} + func TestSelfReferentialBelongsToOverrideReferences(t *testing.T) { type User struct { ID int32 `gorm:"primaryKey"` @@ -144,6 +163,25 @@ func TestHasOneWithOnlyReferences(t *testing.T) { }) } +func TestHasOneWithOnlyReferences2(t *testing.T) { + type Profile struct { + gorm.Model + Name string + UserID 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", "UserID", "Profile", "", true}}, + }) +} + func TestHasManyOverrideForeignKey(t *testing.T) { type Profile struct { gorm.Model