Fix preload error when result is empty

This commit is contained in:
Jinzhu 2015-03-02 10:52:18 +08:00
parent b391029188
commit b3d6025365
1 changed files with 52 additions and 46 deletions

View File

@ -34,8 +34,9 @@ func Preload(scope *Scope) {
switch relation.Kind { switch relation.Kind {
case "has_one": case "has_one":
if primaryKeys := scope.getColumnAsArray(primaryName); len(primaryKeys) > 0 {
condition := fmt.Sprintf("%v IN (?)", scope.Quote(relation.ForeignDBName)) condition := fmt.Sprintf("%v IN (?)", scope.Quote(relation.ForeignDBName))
scope.NewDB().Where(condition, scope.getColumnAsArray(primaryName)).Find(results, conditions...) scope.NewDB().Where(condition, primaryKeys).Find(results, conditions...)
resultValues := reflect.Indirect(reflect.ValueOf(results)) resultValues := reflect.Indirect(reflect.ValueOf(results))
for i := 0; i < resultValues.Len(); i++ { for i := 0; i < resultValues.Len(); i++ {
@ -53,9 +54,11 @@ func Preload(scope *Scope) {
scope.SetColumn(field, result) scope.SetColumn(field, result)
} }
} }
}
case "has_many": case "has_many":
if primaryKeys := scope.getColumnAsArray(primaryName); len(primaryKeys) > 0 {
condition := fmt.Sprintf("%v IN (?)", scope.Quote(relation.ForeignDBName)) condition := fmt.Sprintf("%v IN (?)", scope.Quote(relation.ForeignDBName))
scope.NewDB().Where(condition, scope.getColumnAsArray(primaryName)).Find(results, conditions...) scope.NewDB().Where(condition, primaryKeys).Find(results, conditions...)
resultValues := reflect.Indirect(reflect.ValueOf(results)) resultValues := reflect.Indirect(reflect.ValueOf(results))
if isSlice { if isSlice {
for i := 0; i < resultValues.Len(); i++ { for i := 0; i < resultValues.Len(); i++ {
@ -74,8 +77,10 @@ func Preload(scope *Scope) {
} else { } else {
scope.SetColumn(field, resultValues) scope.SetColumn(field, resultValues)
} }
}
case "belongs_to": case "belongs_to":
scope.NewDB().Where(scope.getColumnAsArray(relation.ForeignFieldName)).Find(results, conditions...) if primaryKeys := scope.getColumnAsArray(relation.ForeignFieldName); len(primaryKeys) > 0 {
scope.NewDB().Where(primaryKeys).Find(results, conditions...)
resultValues := reflect.Indirect(reflect.ValueOf(results)) resultValues := reflect.Indirect(reflect.ValueOf(results))
for i := 0; i < resultValues.Len(); i++ { for i := 0; i < resultValues.Len(); i++ {
result := resultValues.Index(i) result := resultValues.Index(i)
@ -92,6 +97,7 @@ func Preload(scope *Scope) {
scope.SetColumn(field, result) scope.SetColumn(field, result)
} }
} }
}
case "many_to_many": case "many_to_many":
scope.Err(errors.New("not supported relation")) scope.Err(errors.New("not supported relation"))
default: default: