From 0546b59743ec2759051cb921a4dc5f7c31f36e3d Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Wed, 22 Jul 2020 11:28:00 +0800 Subject: [PATCH] Fix save many2many associations with UUID primary key, close #3182 --- callbacks/create.go | 9 ++++++++- tests/postgres_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/callbacks/create.go b/callbacks/create.go index eecb80a1..de5bf1f8 100644 --- a/callbacks/create.go +++ b/callbacks/create.go @@ -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 } diff --git a/tests/postgres_test.go b/tests/postgres_test.go index 98302d87..ab47a548 100644 --- a/tests/postgres_test.go +++ b/tests/postgres_test.go @@ -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) + } +}