diff --git a/callback_query_preload.go b/callback_query_preload.go index efa65bb5..b3fd4fb4 100644 --- a/callback_query_preload.go +++ b/callback_query_preload.go @@ -186,9 +186,11 @@ func (scope *Scope) handleHasManyPreload(field *Field, conditions []interface{}) for j := 0; j < indirectScopeValue.Len(); j++ { object := indirect(indirectScopeValue.Index(j)) objectRealValue := getValueFromFields(object, relation.AssociationForeignFieldNames) + f := object.FieldByName(field.Name) if results, ok := preloadMap[toString(objectRealValue)]; ok { - f := object.FieldByName(field.Name) f.Set(reflect.Append(f, results...)) + } else { + f.Set(reflect.MakeSlice(f.Type(), 0, 0)) } } } else { diff --git a/preload_test.go b/preload_test.go index 8c56a8ac..6ca6980c 100644 --- a/preload_test.go +++ b/preload_test.go @@ -90,6 +90,8 @@ func TestPreload(t *testing.T) { } } else if len(user.Emails) != 0 { t.Errorf("should not preload any emails for other users when with condition") + } else if user.Emails == nil { + t.Errorf("should return an empty slice to indicate zero results") } } } @@ -592,8 +594,14 @@ func TestNestedPreload9(t *testing.T) { }, Level2_1: Level2_1{ Level1s: []Level1{ - {Value: "value3-3"}, - {Value: "value4-4"}, + { + Value: "value3-3", + Level0s: []Level0{}, + }, + { + Value: "value4-4", + Level0s: []Level0{}, + }, }, }, } @@ -657,6 +665,7 @@ func TestNestedPreload10(t *testing.T) { }, { Value: "bar 2", + LevelA3s: []*LevelA3{}, }, } for _, levelA2 := range want {