Add more preloading many2many tests

This commit is contained in:
Jinzhu 2015-08-18 07:47:00 +08:00
parent a24417824d
commit 7ec2b87312
1 changed files with 80 additions and 0 deletions

View File

@ -604,6 +604,86 @@ func TestNestedPreload9(t *testing.T) {
} }
func TestManyToManyPreload(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 ( type (
Level1 struct { Level1 struct {
ID uint `gorm:"primary_key;"` ID uint `gorm:"primary_key;"`