Merge pull request #2330 from xwjdsh/bugfix/return-empty-slice-many2many

Return empty slice for many2many if no asscociation was found
This commit is contained in:
Emir Beganović 2019-04-11 09:31:25 +02:00 committed by GitHub
commit efcabc8be3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 5 deletions

View File

@ -391,14 +391,20 @@ func (scope *Scope) handleManyToManyPreload(field *Field, conditions []interface
key := toString(getValueFromFields(indirectScopeValue, foreignFieldNames)) key := toString(getValueFromFields(indirectScopeValue, foreignFieldNames))
fieldsSourceMap[key] = append(fieldsSourceMap[key], indirectScopeValue.FieldByName(field.Name)) fieldsSourceMap[key] = append(fieldsSourceMap[key], indirectScopeValue.FieldByName(field.Name))
} }
for source, link := range linkHash {
for i, field := range fieldsSourceMap[source] { for source, fields := range fieldsSourceMap {
for _, f := range fields {
//If not 0 this means Value is a pointer and we already added preloaded models to it //If not 0 this means Value is a pointer and we already added preloaded models to it
if fieldsSourceMap[source][i].Len() != 0 { if f.Len() != 0 {
continue continue
} }
field.Set(reflect.Append(fieldsSourceMap[source][i], link...))
}
v := reflect.MakeSlice(f.Type(), 0, 0)
if len(linkHash[source]) > 0 {
v = reflect.Append(f, linkHash[source]...)
}
f.Set(v)
}
} }
} }

View File

@ -771,6 +771,7 @@ func TestNestedPreload11(t *testing.T) {
levelB3 := &LevelB3{ levelB3 := &LevelB3{
Value: "bar", Value: "bar",
LevelB1ID: sql.NullInt64{Valid: true, Int64: int64(levelB1.ID)}, LevelB1ID: sql.NullInt64{Valid: true, Int64: int64(levelB1.ID)},
LevelB2s: []*LevelB2{},
} }
if err := DB.Create(levelB3).Error; err != nil { if err := DB.Create(levelB3).Error; err != nil {
t.Error(err) t.Error(err)