diff --git a/association_test.go b/association_test.go index 8ba198e5..90ad4298 100644 --- a/association_test.go +++ b/association_test.go @@ -5,6 +5,8 @@ import ( "reflect" "sort" "testing" + + "github.com/jinzhu/gorm" ) func TestBelongsTo(t *testing.T) { @@ -177,6 +179,49 @@ func TestBelongsTo(t *testing.T) { } } +func TestBelongsToOverrideForeignKey1(t *testing.T) { + type Profile struct { + gorm.Model + Name string + } + + type User struct { + gorm.Model + Profile Profile `gorm:"ForeignKey:ProfileRefer"` + ProfileRefer int + } + + DB.AutoMigrate(&User{}) + DB.AutoMigrate(&Profile{}) + + var user = User{Model: gorm.Model{ID: 1}, ProfileRefer: 10} + if err := DB.Model(&user).Association("Profile").Find(&[]Profile{}).Error; err != nil { + t.Errorf("Override belongs to foreign key with tag") + } +} + +func TestBelongsToOverrideForeignKey2(t *testing.T) { + type Profile struct { + gorm.Model + Refer string + Name string + } + + type User struct { + gorm.Model + Profile Profile `gorm:"ForeignKey:ProfileID;AssociationForeignKey:Refer"` + ProfileID int + } + + DB.AutoMigrate(&User{}) + DB.AutoMigrate(&Profile{}) + + var user = User{Model: gorm.Model{ID: 1}, ProfileID: 10} + if err := DB.Model(&user).Association("Profile").Find(&[]Profile{}).Error; err != nil { + t.Errorf("Override belongs to foreign key with tag") + } +} + func TestHasOne(t *testing.T) { user := User{ Name: "has one", diff --git a/model_struct.go b/model_struct.go index b0dccf3b..a0d52352 100644 --- a/model_struct.go +++ b/model_struct.go @@ -447,7 +447,10 @@ func (scope *Scope) GetModelStruct() *ModelStruct { if len(associationForeignKeys) == 0 { for _, foreignKey := range foreignKeys { if strings.HasPrefix(foreignKey, field.Name) { - associationForeignKeys = append(associationForeignKeys, strings.TrimPrefix(foreignKey, field.Name)) + associationForeignKey := strings.TrimPrefix(foreignKey, field.Name) + if foreignField := getForeignField(associationForeignKey, toFields); foreignField != nil { + associationForeignKeys = append(associationForeignKeys, associationForeignKey) + } } } if len(associationForeignKeys) == 0 && len(foreignKeys) == 1 {