Refactor cascade delete associations

This commit is contained in:
Jinzhu 2020-09-15 14:28:26 +08:00
parent 06d534d6ea
commit a932175ccf
2 changed files with 14 additions and 2 deletions

View File

@ -2,6 +2,7 @@ package callbacks
import ( import (
"reflect" "reflect"
"strings"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
@ -37,7 +38,18 @@ func DeleteBeforeAssociations(db *gorm.DB) {
withoutConditions := false withoutConditions := false
if len(db.Statement.Selects) > 0 { 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 { for _, cond := range queryConds {

View File

@ -136,7 +136,7 @@ func TestDeleteWithAssociations(t *testing.T) {
t.Fatalf("failed to create user, got error %v", err) 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) t.Fatalf("failed to delete user, got error %v", err)
} }