From 06d534d6eaa7f8534e51742b9930818511aaf28c Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 15 Sep 2020 12:41:45 +0800 Subject: [PATCH] Cascade delete associations, close #3473 --- callbacks/delete.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/callbacks/delete.go b/callbacks/delete.go index 510dfae4..549a94e7 100644 --- a/callbacks/delete.go +++ b/callbacks/delete.go @@ -34,8 +34,23 @@ func DeleteBeforeAssociations(db *gorm.DB) { queryConds := rel.ToQueryConditions(db.Statement.ReflectValue) modelValue := reflect.New(rel.FieldSchema.ModelType).Interface() tx := db.Session(&gorm.Session{}).Model(modelValue) - if db.AddError(tx.Clauses(clause.Where{Exprs: queryConds}).Delete(modelValue).Error) != nil { - return + withoutConditions := false + + if len(db.Statement.Selects) > 0 { + tx = tx.Select(db.Statement.Selects) + } + + for _, cond := range queryConds { + if c, ok := cond.(clause.IN); ok && len(c.Values) == 0 { + withoutConditions = true + break + } + } + + if !withoutConditions { + if db.AddError(tx.Clauses(clause.Where{Exprs: queryConds}).Delete(modelValue).Error) != nil { + return + } } case schema.Many2Many: var (