From c6a22c50962028255a718f22fe7e8959e8c67884 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Wed, 16 Dec 2015 10:40:57 +0800 Subject: [PATCH] Refact fix invalid zero value for Preload --- preload.go | 30 +++++++++++------------------- 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/preload.go b/preload.go index f3f9dabc..69efc01b 100644 --- a/preload.go +++ b/preload.go @@ -9,20 +9,18 @@ import ( ) func getRealValue(value reflect.Value, columns []string) (results []interface{}) { - for _, column := range columns { - pointedValue := reflect.Indirect(value) - // If v is a nil pointer, Indirect returns a zero Value! - // Therefor we need to check for a zero value, - // as FieldByName could panic - if !pointedValue.IsValid() { - continue - } - if pointedValue.FieldByName(column).IsValid() { - result := pointedValue.FieldByName(column).Interface() - if r, ok := result.(driver.Valuer); ok { - result, _ = r.Value() + // If value is a nil pointer, Indirect returns a zero Value! + // Therefor we need to check for a zero value, + // as FieldByName could panic + if pointedValue := reflect.Indirect(value); pointedValue.IsValid() { + for _, column := range columns { + if pointedValue.FieldByName(column).IsValid() { + result := pointedValue.FieldByName(column).Interface() + if r, ok := result.(driver.Valuer); ok { + result, _ = r.Value() + } + results = append(results, result) } - results = append(results, result) } } return @@ -297,12 +295,6 @@ func (scope *Scope) handleManyToManyPreload(field *Field, conditions []interface } } } else { - // If v is a nil pointer, Indirect returns a zero Value! - // Therefor we need to check for a zero value, - // as FieldByName could panic - if !scope.IndirectValue().IsValid() { - return - } object := scope.IndirectValue() source := getRealValue(object, associationForeignStructFieldNames) field := object.FieldByName(field.Name)