gdb_model_delete.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright GoFrame Author(https://github.com/gogf/gf). 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/gerror"
  11. "github.com/gogf/gf/os/gtime"
  12. "github.com/gogf/gf/text/gstr"
  13. )
  14. // Delete does "DELETE FROM ... " statement for the model.
  15. // The optional parameter <where> is the same as the parameter of Model.Where function,
  16. // see Model.Where.
  17. func (m *Model) Delete(where ...interface{}) (result sql.Result, err error) {
  18. if len(where) > 0 {
  19. return m.Where(where[0], where[1:]...).Delete()
  20. }
  21. defer func() {
  22. if err == nil {
  23. m.checkAndRemoveCache()
  24. }
  25. }()
  26. var (
  27. fieldNameDelete = m.getSoftFieldNameDeleted()
  28. conditionWhere, conditionExtra, conditionArgs = m.formatCondition(false, false)
  29. )
  30. // Soft deleting.
  31. if !m.unscoped && fieldNameDelete != "" {
  32. return m.db.DoUpdate(
  33. m.getLink(true),
  34. m.tables,
  35. fmt.Sprintf(`%s=?`, m.db.QuoteString(fieldNameDelete)),
  36. conditionWhere+conditionExtra,
  37. append([]interface{}{gtime.Now().String()}, conditionArgs...),
  38. )
  39. }
  40. conditionStr := conditionWhere + conditionExtra
  41. if !gstr.ContainsI(conditionStr, " WHERE ") {
  42. return nil, gerror.New("there should be WHERE condition statement for DELETE operation")
  43. }
  44. return m.db.DoDelete(m.getLink(true), m.tables, conditionStr, conditionArgs...)
  45. }