From a932175ccf98130aaa3028b75daf047a32b6dca0 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 15 Sep 2020 14:28:26 +0800 Subject: [PATCH] Refactor cascade delete associations --- callbacks/delete.go | 14 +++++++++++++- tests/delete_test.go | 2 +- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/callbacks/delete.go b/callbacks/delete.go index 549a94e7..85f11f4b 100644 --- a/callbacks/delete.go +++ b/callbacks/delete.go @@ -2,6 +2,7 @@ package callbacks import ( "reflect" + "strings" "gorm.io/gorm" "gorm.io/gorm/clause" @@ -37,7 +38,18 @@ func DeleteBeforeAssociations(db *gorm.DB) { withoutConditions := false if len(db.Statement.Selects) > 0 { - tx = tx.Select(db.Statement.Selects) + var selects []string + for _, s := range db.Statement.Selects { + if s == clause.Associations { + selects = append(selects, s) + } else if strings.HasPrefix(s, column+".") { + selects = append(selects, strings.TrimPrefix(s, column+".")) + } + } + + if len(selects) > 0 { + tx = tx.Select(selects) + } } for _, cond := range queryConds { diff --git a/tests/delete_test.go b/tests/delete_test.go index 4945e837..ecd5ec39 100644 --- a/tests/delete_test.go +++ b/tests/delete_test.go @@ -136,7 +136,7 @@ func TestDeleteWithAssociations(t *testing.T) { t.Fatalf("failed to create user, got error %v", err) } - if err := DB.Select(clause.Associations).Delete(&user).Error; err != nil { + if err := DB.Select(clause.Associations, "Pets.Toy").Delete(&user).Error; err != nil { t.Fatalf("failed to delete user, got error %v", err) }