gdb_model_delete.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gdb
  7. import (
  8. "database/sql"
  9. "fmt"
  10. "github.com/gogf/gf/errors/gcode"
  11. "github.com/gogf/gf/errors/gerror"
  12. "github.com/gogf/gf/os/gtime"
  13. "github.com/gogf/gf/text/gstr"
  14. )
  15. // Delete does "DELETE FROM ... " statement for the model.
  16. // The optional parameter `where` is the same as the parameter of Model.Where function,
  17. // see Model.Where.
  18. func (m *Model) Delete(where ...interface{}) (result sql.Result, err error) {
  19. if len(where) > 0 {
  20. return m.Where(where[0], where[1:]...).Delete()
  21. }
  22. defer func() {
  23. if err == nil {
  24. m.checkAndRemoveCache()
  25. }
  26. }()
  27. var (
  28. fieldNameDelete = m.getSoftFieldNameDeleted()
  29. conditionWhere, conditionExtra, conditionArgs = m.formatCondition(false, false)
  30. )
  31. // Soft deleting.
  32. if !m.unscoped && fieldNameDelete != "" {
  33. return m.db.DoUpdate(
  34. m.GetCtx(),
  35. m.getLink(true),
  36. m.tables,
  37. fmt.Sprintf(`%s=?`, m.db.GetCore().QuoteString(fieldNameDelete)),
  38. conditionWhere+conditionExtra,
  39. append([]interface{}{gtime.Now().String()}, conditionArgs...),
  40. )
  41. }
  42. conditionStr := conditionWhere + conditionExtra
  43. if !gstr.ContainsI(conditionStr, " WHERE ") {
  44. return nil, gerror.NewCode(gcode.CodeMissingParameter, "there should be WHERE condition statement for DELETE operation")
  45. }
  46. return m.db.DoDelete(m.GetCtx(), m.getLink(true), m.tables, conditionStr, conditionArgs...)
  47. }