From 7ec2b87312d3f694096acef64f8c773c556f5675 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 18 Aug 2015 07:47:00 +0800 Subject: [PATCH] Add more preloading many2many tests --- preload_test.go | 80 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/preload_test.go b/preload_test.go index 043e24d6..cde0e739 100644 --- a/preload_test.go +++ b/preload_test.go @@ -604,6 +604,86 @@ 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{ + {Value: "ru"}, + {Value: "en"}, + }} + if err := DB.Save(&want).Error; err != nil { + panic(err) + } + + want2 := Level2{Value: "Tom", Level1s: []Level1{ + {Value: "zh"}, + {Value: "de"}, + }} + if err := DB.Save(&want2).Error; err != nil { + panic(err) + } + + var got Level2 + if err := DB.Preload("Level1s").Find(&got, "value = ?", "Bob").Error; err != nil { + panic(err) + } + + if !reflect.DeepEqual(got, want) { + t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) + } + + var got2 Level2 + if err := DB.Preload("Level1s").Find(&got2, "value = ?", "Tom").Error; err != nil { + panic(err) + } + + if !reflect.DeepEqual(got2, want2) { + t.Errorf("got %s; want %s", toJSONString(got2), toJSONString(want2)) + } + + var got3 []Level2 + if err := DB.Preload("Level1s").Find(&got3, "value IN (?)", []string{"Bob", "Tom"}).Error; err != nil { + panic(err) + } + + if !reflect.DeepEqual(got3, []Level2{got, got2}) { + t.Errorf("got %s; want %s", toJSONString(got3), toJSONString([]Level2{got, got2})) + } + + var got4 []Level2 + if err := DB.Preload("Level1s", "value IN (?)", []string{"zh", "ru"}).Find(&got4, "value IN (?)", []string{"Bob", "Tom"}).Error; err != nil { + panic(err) + } + + var ruLevel1 Level1 + var zhLevel1 Level1 + DB.First(&ruLevel1, "value = ?", "ru") + DB.First(&zhLevel1, "value = ?", "zh") + + got.Level1s = []Level1{ruLevel1} + got2.Level1s = []Level1{zhLevel1} + if !reflect.DeepEqual(got4, []Level2{got, got2}) { + t.Errorf("got %s; want %s", toJSONString(got4), toJSONString([]Level2{got, got2})) + } +} + +func TestManyToManyPreloadForPointer(t *testing.T) { type ( Level1 struct { ID uint `gorm:"primary_key;"`