mirror of https://github.com/go-gorm/gorm.git
Allow to skip associations when creating join table for many2many, close #3605
This commit is contained in:
parent
694e42d6a1
commit
50df9da6a1
|
@ -291,7 +291,9 @@ func SaveAfterAssociations(db *gorm.DB) {
|
|||
}
|
||||
|
||||
if elems.Len() > 0 {
|
||||
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))
|
||||
|
|
|
@ -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}),
|
||||
|
|
Loading…
Reference in New Issue