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)
preloadMap[toString(value)] = append(preloadMap[toString(value)], result)
}
objects := scope.IndirectValue() objects := scope.IndirectValue()
for j := 0; j < objects.Len(); j++ { for j := 0; j < objects.Len(); j++ {
object := reflect.Indirect(objects.Index(j)) object := reflect.Indirect(objects.Index(j))
if equalAsString(getRealValue(object, relation.AssociationForeignFieldNames), value) { objectRealValue := getRealValue(object, relation.AssociationForeignFieldNames)
objectStringValue := toString(objectRealValue)
if results, ok := preloadMap[objectStringValue]; ok {
if object.Kind() == reflect.Ptr { if object.Kind() == reflect.Ptr {
object = object.Elem() object = object.Elem()
} }
f := object.FieldByName(field.Name) f := object.FieldByName(field.Name)
f.Set(reflect.Append(f, result)) f.Set(reflect.Append(f, results...))
break
}
} }
} }
} else { } else {