diff --git a/association_test.go b/association_test.go index 51a0c553..3ffd8880 100644 --- a/association_test.go +++ b/association_test.go @@ -64,6 +64,7 @@ func TestRelated(t *testing.T) { ShippingAddress: Address{Address1: "Shipping Address - Address 1"}, Emails: []Email{{Email: "jinzhu@example.com"}, {Email: "jinzhu-2@example@example.com"}}, CreditCard: CreditCard{Number: "1234567890"}, + Company: Company{Name: "company1"}, } DB.Save(&user) @@ -127,6 +128,11 @@ func TestRelated(t *testing.T) { if !DB.Model(&CreditCard{}).Related(&User{}).RecordNotFound() { t.Errorf("RecordNotFound for Related") } + + var company Company + if DB.Model(&user).Related(&company, "Company").RecordNotFound() || company.Name != "company1" { + t.Errorf("RecordNotFound for Related") + } } func TestManyToMany(t *testing.T) { diff --git a/scope_private.go b/scope_private.go index 433e364a..f11ee901 100644 --- a/scope_private.go +++ b/scope_private.go @@ -413,7 +413,8 @@ func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope { scope.Err(toScope.db.Joins(joinSql).Where(whereSql, scope.PrimaryKeyValue()).Find(value).Error) } else if relationship.Kind == "belongs_to" { sql := fmt.Sprintf("%v = ?", scope.Quote(toScope.PrimaryKey())) - scope.Err(toScope.db.Where(sql, fromField.Field.Interface()).Find(value).Error) + foreignKeyValue := fromFields[relationship.ForeignDBName].Field.Interface() + scope.Err(toScope.db.Where(sql, foreignKeyValue).Find(value).Error) } else if relationship.Kind == "has_many" || relationship.Kind == "has_one" { sql := fmt.Sprintf("%v = ?", scope.Quote(relationship.ForeignDBName)) query := toScope.db.Where(sql, scope.PrimaryKeyValue())