From f35dee5531fccaf56720c659898da1835001b315 Mon Sep 17 00:00:00 2001 From: kimiby Date: Sun, 16 Aug 2015 12:25:25 +0300 Subject: [PATCH] preload_m2m fix and test --- preload.go | 16 ++++++++++++++++ preload_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/preload.go b/preload.go index 75be26dc..dd19a8bc 100644 --- a/preload.go +++ b/preload.go @@ -297,6 +297,22 @@ func (scope *Scope) handleHasManyToManyPreload(field *Field, conditions []interf } } } + } else { + object := scope.IndirectValue() + var checked []string + source := getRealValue(object, relation.AssociationForeignFieldNames) + + for i := 0; i < results.Len(); i++ { + result := results.Index(i) + value := getRealValue(result, relation.ForeignFieldNames) + + if strInSlice(toString(value), linkHash[toString(source)]) && !strInSlice(toString(value), checked) { + f := object.FieldByName(field.Name) + f.Set(reflect.Append(f, result)) + checked = append(checked, toString(value)) + continue + } + } } } diff --git a/preload_test.go b/preload_test.go index a6647bbd..aec6d816 100644 --- a/preload_test.go +++ b/preload_test.go @@ -603,6 +603,44 @@ func TestNestedPreload9(t *testing.T) { } } +func TestManyToManyPreload(t *testing.T) { + type ( + Level1 struct { + ID uint `gorm:"primary_key;"` + Value string + } + Level2 struct { + ID uint `gorm:"primary_key;"` + Value string + Level1s []Level1 `gorm:"many2many:levels;"` + } + ) + + DB.DropTableIfExists(&Level2{}) + DB.DropTableIfExists(&Level1{}) + + if err := DB.AutoMigrate(&Level2{}, &Level1{}).Error; err != nil { + panic(err) + } + + want := Level2{Value: "Bob", Level1s: []Level1{ + Level1{Value: "ru"}, + Level1{Value: "en"}, + }} + if err := DB.Save(&want).Error; err != nil { + panic(err) + } + + var got Level2 + if err := DB.Preload("Level1s").Find(&got).Error; err != nil { + panic(err) + } + + if !reflect.DeepEqual(got, want) { + t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) + } +} + func toJSONString(v interface{}) []byte { r, _ := json.MarshalIndent(v, "", " ") return r