2020-05-30 11:03:27 +03:00
|
|
|
package tests_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
|
|
|
|
2020-09-24 14:28:52 +03:00
|
|
|
"gorm.io/gorm"
|
2020-06-02 05:34:50 +03:00
|
|
|
. "gorm.io/gorm/utils/tests"
|
2020-05-30 11:03:27 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestUpdateMany2ManyAssociations(t *testing.T) {
|
2022-01-06 10:02:53 +03:00
|
|
|
user := *GetUser("update-many2many", Config{})
|
2020-05-30 11:03:27 +03:00
|
|
|
|
|
|
|
if err := DB.Create(&user).Error; err != nil {
|
|
|
|
t.Fatalf("errors happened when create: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
user.Languages = []Language{{Code: "zh-CN", Name: "Chinese"}, {Code: "en", Name: "English"}}
|
|
|
|
for _, lang := range user.Languages {
|
|
|
|
DB.Create(&lang)
|
|
|
|
}
|
|
|
|
user.Friends = []*User{{Name: "friend-1"}, {Name: "friend-2"}}
|
|
|
|
|
|
|
|
if err := DB.Save(&user).Error; err != nil {
|
|
|
|
t.Fatalf("errors happened when update: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
var user2 User
|
|
|
|
DB.Preload("Languages").Preload("Friends").Find(&user2, "id = ?", user.ID)
|
|
|
|
CheckUser(t, user2, user)
|
2020-09-24 14:28:52 +03:00
|
|
|
|
|
|
|
for idx := range user.Friends {
|
|
|
|
user.Friends[idx].Name += "new"
|
|
|
|
}
|
|
|
|
|
|
|
|
for idx := range user.Languages {
|
|
|
|
user.Languages[idx].Name += "new"
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := DB.Save(&user).Error; err != nil {
|
|
|
|
t.Fatalf("errors happened when update: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
var user3 User
|
|
|
|
DB.Preload("Languages").Preload("Friends").Find(&user3, "id = ?", user.ID)
|
|
|
|
CheckUser(t, user2, user3)
|
|
|
|
|
|
|
|
if err := DB.Session(&gorm.Session{FullSaveAssociations: true}).Save(&user).Error; err != nil {
|
|
|
|
t.Fatalf("errors happened when update: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
var user4 User
|
|
|
|
DB.Preload("Languages").Preload("Friends").Find(&user4, "id = ?", user.ID)
|
|
|
|
CheckUser(t, user4, user)
|
2020-05-30 11:03:27 +03:00
|
|
|
}
|