forked from mirror/gorm
Fix preload error when result is empty
This commit is contained in:
parent
b391029188
commit
b3d6025365
12
preload.go
12
preload.go
|
@ -34,8 +34,9 @@ func Preload(scope *Scope) {
|
|||
|
||||
switch relation.Kind {
|
||||
case "has_one":
|
||||
if primaryKeys := scope.getColumnAsArray(primaryName); len(primaryKeys) > 0 {
|
||||
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))
|
||||
for i := 0; i < resultValues.Len(); i++ {
|
||||
|
@ -53,9 +54,11 @@ func Preload(scope *Scope) {
|
|||
scope.SetColumn(field, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
case "has_many":
|
||||
if primaryKeys := scope.getColumnAsArray(primaryName); len(primaryKeys) > 0 {
|
||||
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))
|
||||
if isSlice {
|
||||
for i := 0; i < resultValues.Len(); i++ {
|
||||
|
@ -74,8 +77,10 @@ func Preload(scope *Scope) {
|
|||
} else {
|
||||
scope.SetColumn(field, resultValues)
|
||||
}
|
||||
}
|
||||
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))
|
||||
for i := 0; i < resultValues.Len(); i++ {
|
||||
result := resultValues.Index(i)
|
||||
|
@ -92,6 +97,7 @@ func Preload(scope *Scope) {
|
|||
scope.SetColumn(field, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
case "many_to_many":
|
||||
scope.Err(errors.New("not supported relation"))
|
||||
default:
|
||||
|
|
Loading…
Reference in New Issue