Cascade delete associations, close #3473

This commit is contained in:
Jinzhu 2020-09-15 12:41:45 +08:00
parent 1d5f910b6e
commit 06d534d6ea
1 changed files with 17 additions and 2 deletions

View File

@ -34,9 +34,24 @@ 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)
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 (
queryConds []clause.Expression