Merge pull request #861 from sunprophit/Issue-860

Issue-860. Preload performance
This commit is contained in:
Jinzhu 2016-03-01 07:51:58 +08:00
commit e1df3994fb
1 changed files with 14 additions and 10 deletions

View File

@ -150,20 +150,24 @@ func (scope *Scope) handleHasManyPreload(field *Field, conditions []interface{})
resultValues := reflect.Indirect(reflect.ValueOf(results)) resultValues := reflect.Indirect(reflect.ValueOf(results))
if scope.IndirectValue().Kind() == reflect.Slice { if scope.IndirectValue().Kind() == reflect.Slice {
preloadMap := make(map[string][]reflect.Value)
for i := 0; i < resultValues.Len(); i++ { for i := 0; i < resultValues.Len(); i++ {
result := resultValues.Index(i) result := resultValues.Index(i)
value := getRealValue(result, relation.ForeignFieldNames) value := getRealValue(result, relation.ForeignFieldNames)
objects := scope.IndirectValue() preloadMap[toString(value)] = append(preloadMap[toString(value)], result)
for j := 0; j < objects.Len(); j++ { }
object := reflect.Indirect(objects.Index(j))
if equalAsString(getRealValue(object, relation.AssociationForeignFieldNames), value) { objects := scope.IndirectValue()
if object.Kind() == reflect.Ptr { for j := 0; j < objects.Len(); j++ {
object = object.Elem() object := reflect.Indirect(objects.Index(j))
} objectRealValue := getRealValue(object, relation.AssociationForeignFieldNames)
f := object.FieldByName(field.Name) objectStringValue := toString(objectRealValue)
f.Set(reflect.Append(f, result)) if results, ok := preloadMap[objectStringValue]; ok {
break if object.Kind() == reflect.Ptr {
object = object.Elem()
} }
f := object.FieldByName(field.Name)
f.Set(reflect.Append(f, results...))
} }
} }
} else { } else {