Skip to content

Commit 883c32e

Browse files
committed
Support Unscoped when delete with selected associations, close #4062
1 parent deff059 commit 883c32e

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

callbacks/delete.go

+3
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ func DeleteBeforeAssociations(db *gorm.DB) {
3636
modelValue := reflect.New(rel.FieldSchema.ModelType).Interface()
3737
tx := db.Session(&gorm.Session{NewDB: true}).Model(modelValue)
3838
withoutConditions := false
39+
if db.Statement.Unscoped {
40+
tx = tx.Unscoped()
41+
}
3942

4043
if len(db.Statement.Selects) > 0 {
4144
var selects []string

tests/delete_test.go

+24
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,30 @@ func TestDeleteWithAssociations(t *testing.T) {
153153
}
154154
}
155155

156+
func TestDeleteAssociationsWithUnscoped(t *testing.T) {
157+
user := GetUser("unscoped_delete_with_associations", Config{Account: true, Pets: 2, Toys: 4, Company: true, Manager: true, Team: 1, Languages: 1, Friends: 1})
158+
159+
if err := DB.Create(user).Error; err != nil {
160+
t.Fatalf("failed to create user, got error %v", err)
161+
}
162+
163+
if err := DB.Unscoped().Select(clause.Associations, "Pets.Toy").Delete(&user).Error; err != nil {
164+
t.Fatalf("failed to delete user, got error %v", err)
165+
}
166+
167+
for key, value := range map[string]int64{"Account": 0, "Pets": 0, "Toys": 0, "Company": 1, "Manager": 1, "Team": 0, "Languages": 0, "Friends": 0} {
168+
if count := DB.Unscoped().Model(&user).Association(key).Count(); count != value {
169+
t.Errorf("user's %v expects: %v, got %v", key, value, count)
170+
}
171+
}
172+
173+
for key, value := range map[string]int64{"Account": 0, "Pets": 0, "Toys": 0, "Company": 1, "Manager": 1, "Team": 0, "Languages": 0, "Friends": 0} {
174+
if count := DB.Model(&user).Association(key).Count(); count != value {
175+
t.Errorf("user's %v expects: %v, got %v", key, value, count)
176+
}
177+
}
178+
}
179+
156180
func TestDeleteSliceWithAssociations(t *testing.T) {
157181
users := []User{
158182
*GetUser("delete_slice_with_associations1", Config{Account: true, Pets: 4, Toys: 1, Company: true, Manager: true, Team: 1, Languages: 1, Friends: 4}),

0 commit comments

Comments
 (0)