Fix save many2many associations with UUID primary key, close #3182

This commit is contained in:
Jinzhu 2020-07-22 11:28:00 +08:00
parent ef002fd7ac
commit 0546b59743
2 changed files with 41 additions and 1 deletions

View File

@ -149,10 +149,17 @@ func CreateWithReturning(db *gorm.DB) {
for rows.Next() {
BEGIN:
reflectValue := db.Statement.ReflectValue.Index(int(db.RowsAffected))
for idx, field := range fields {
fieldValue := field.ReflectValueOf(db.Statement.ReflectValue.Index(int(db.RowsAffected)))
fieldValue := field.ReflectValueOf(reflectValue)
if onConflict.DoNothing && !fieldValue.IsZero() {
db.RowsAffected++
if int(db.RowsAffected) >= db.Statement.ReflectValue.Len() {
return
}
goto BEGIN
}

View File

@ -37,3 +37,36 @@ func TestPostgres(t *testing.T) {
t.Errorf("No error should happen, but got %v", err)
}
}
type Post struct {
ID uuid.UUID `gorm:"primary_key;type:uuid;default:uuid_generate_v4()"`
Title string
Categories []*Category `gorm:"Many2Many:post_categories"`
}
type Category struct {
ID uuid.UUID `gorm:"primary_key;type:uuid;default:uuid_generate_v4()"`
Title string
Posts []*Post `gorm:"Many2Many:post_categories"`
}
func TestMany2ManyWithDefaultValueUUID(t *testing.T) {
if DB.Dialector.Name() != "postgres" {
t.Skip()
}
DB.Migrator().DropTable(&Post{}, &Category{}, "post_categories")
DB.AutoMigrate(&Post{}, &Category{})
post := Post{
Title: "Hello World",
Categories: []*Category{
{Title: "Coding"},
{Title: "Golang"},
},
}
if err := DB.Create(&post).Error; err != nil {
t.Errorf("Failed, got error: %v", err)
}
}