From 50df9da6a1821cfd5bc5100dcbd007ad9defa1d8 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 17 Nov 2020 20:24:08 +0800 Subject: [PATCH] Allow to skip associations when creating join table for many2many, close #3605 --- callbacks/associations.go | 4 +++- tests/associations_many2many_test.go | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/callbacks/associations.go b/callbacks/associations.go index 1702f442..ce91c2ee 100644 --- a/callbacks/associations.go +++ b/callbacks/associations.go @@ -291,7 +291,9 @@ func SaveAfterAssociations(db *gorm.DB) { } if elems.Len() > 0 { - db.AddError(db.Session(&gorm.Session{NewDB: true}).Clauses(onConflictOption(db.Statement, rel.FieldSchema, nil)).Create(elems.Interface()).Error) + if v, ok := selectColumns[rel.Name+".*"]; !ok || v { + db.AddError(db.Session(&gorm.Session{NewDB: true}).Clauses(onConflictOption(db.Statement, rel.FieldSchema, nil)).Create(elems.Interface()).Error) + } for i := 0; i < elems.Len(); i++ { appendToJoins(objs[i], elems.Index(i)) diff --git a/tests/associations_many2many_test.go b/tests/associations_many2many_test.go index 2ecf7b66..1ddd3b85 100644 --- a/tests/associations_many2many_test.go +++ b/tests/associations_many2many_test.go @@ -93,6 +93,28 @@ func TestMany2ManyAssociation(t *testing.T) { AssertAssociationCount(t, user2, "Languages", 0, "after clear") } +func TestMany2ManyOmitAssociations(t *testing.T) { + var user = *GetUser("many2many_omit_associations", Config{Languages: 2}) + + if err := DB.Omit("Languages.*").Create(&user).Error; err == nil { + t.Fatalf("should raise error when create users without languages reference") + } + + if err := DB.Create(&user.Languages).Error; err != nil { + t.Fatalf("no error should happen when create languages, but got %v", err) + } + + if err := DB.Omit("Languages.*").Create(&user).Error; err != nil { + t.Fatalf("no error should happen when create user when languages exists, but got %v", err) + } + + // Find + var languages []Language + if DB.Model(&user).Association("Languages").Find(&languages); len(languages) != 2 { + t.Errorf("languages count should be %v, but got %v", 2, len(languages)) + } +} + func TestMany2ManyAssociationForSlice(t *testing.T) { var users = []User{ *GetUser("slice-many2many-1", Config{Languages: 2}),