diff --git a/queries/eager_load.go b/queries/eager_load.go index 962d722..30c71e4 100644 --- a/queries/eager_load.go +++ b/queries/eager_load.go @@ -5,9 +5,9 @@ import ( "reflect" "strings" - "github.com/pkg/errors" "github.com/lbryio/sqlboiler/boil" "github.com/lbryio/sqlboiler/strmangle" + "github.com/pkg/errors" ) type loadRelationshipState struct { @@ -167,7 +167,7 @@ func (l loadRelationshipState) callLoadFunction(depth int, loadingFrom reflect.V if val.Len() == 0 { return nil } - val = val.Index(0) + val = firstNonNilValue(val) if val.IsNil() { return nil } @@ -190,6 +190,21 @@ func (l loadRelationshipState) callLoadFunction(depth int, loadingFrom reflect.V return nil } +// firstNonNilValue returns the first non nil value of input. If all are nil, return the value with index 0. +func firstNonNilValue(val reflect.Value) reflect.Value { + length := val.Len() + if length == 0 { + // return val itself if val.Len() = 0 + return val + } + for i := 0; i < length; i++ { + if !val.Index(i).IsNil() { + return val.Index(i) + } + } + return val.Index(0) +} + // loadRelationshipsRecurse is a helper function for taking a reflect.Value and // Basically calls loadRelationships with: obj.R.EagerLoadedObj // Called with an obj of *struct