From 883c32e59a0b56a3da972dfc8fb15b9fc281a1ba Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sun, 7 Feb 2021 14:36:27 +0800 Subject: [PATCH] Support Unscoped when delete with selected associations, close #4062 --- callbacks/delete.go | 3 +++ tests/delete_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/callbacks/delete.go b/callbacks/delete.go index 867aa697..128722a1 100644 --- a/callbacks/delete.go +++ b/callbacks/delete.go @@ -36,6 +36,9 @@ func DeleteBeforeAssociations(db *gorm.DB) { modelValue := reflect.New(rel.FieldSchema.ModelType).Interface() tx := db.Session(&gorm.Session{NewDB: true}).Model(modelValue) withoutConditions := false + if db.Statement.Unscoped { + tx = tx.Unscoped() + } if len(db.Statement.Selects) > 0 { var selects []string diff --git a/tests/delete_test.go b/tests/delete_test.go index 37e29fbe..abe85b0e 100644 --- a/tests/delete_test.go +++ b/tests/delete_test.go @@ -153,6 +153,30 @@ func TestDeleteWithAssociations(t *testing.T) { } } +func TestDeleteAssociationsWithUnscoped(t *testing.T) { + user := GetUser("unscoped_delete_with_associations", Config{Account: true, Pets: 2, Toys: 4, Company: true, Manager: true, Team: 1, Languages: 1, Friends: 1}) + + if err := DB.Create(user).Error; err != nil { + t.Fatalf("failed to create user, got error %v", err) + } + + if err := DB.Unscoped().Select(clause.Associations, "Pets.Toy").Delete(&user).Error; err != nil { + t.Fatalf("failed to delete user, got error %v", err) + } + + for key, value := range map[string]int64{"Account": 0, "Pets": 0, "Toys": 0, "Company": 1, "Manager": 1, "Team": 0, "Languages": 0, "Friends": 0} { + if count := DB.Unscoped().Model(&user).Association(key).Count(); count != value { + t.Errorf("user's %v expects: %v, got %v", key, value, count) + } + } + + for key, value := range map[string]int64{"Account": 0, "Pets": 0, "Toys": 0, "Company": 1, "Manager": 1, "Team": 0, "Languages": 0, "Friends": 0} { + if count := DB.Model(&user).Association(key).Count(); count != value { + t.Errorf("user's %v expects: %v, got %v", key, value, count) + } + } +} + func TestDeleteSliceWithAssociations(t *testing.T) { users := []User{ *GetUser("delete_slice_with_associations1", Config{Account: true, Pets: 4, Toys: 1, Company: true, Manager: true, Team: 1, Languages: 1, Friends: 4}),