Fix Related for belongs to association

This commit is contained in:
Jinzhu 2015-03-02 15:55:24 +08:00
parent b3d6025365
commit 61a878dc2d
2 changed files with 8 additions and 1 deletions

View File

@ -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) {

View File

@ -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())