2020-03-13 17:21:30 +08:00
|
|
|
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
|
|
|
|
|
|
|
package gdb
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2020-04-08 21:26:14 +08:00
|
|
|
"fmt"
|
2020-11-06 00:00:41 +08:00
|
|
|
"github.com/gogf/gf/errors/gerror"
|
2020-04-08 21:26:14 +08:00
|
|
|
"github.com/gogf/gf/os/gtime"
|
2020-11-06 00:00:41 +08:00
|
|
|
"github.com/gogf/gf/text/gstr"
|
2020-03-13 17:21:30 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
// Delete does "DELETE FROM ... " statement for the model.
|
|
|
|
// The optional parameter <where> is the same as the parameter of Model.Where function,
|
|
|
|
// see Model.Where.
|
|
|
|
func (m *Model) Delete(where ...interface{}) (result sql.Result, err error) {
|
|
|
|
if len(where) > 0 {
|
|
|
|
return m.Where(where[0], where[1:]...).Delete()
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
if err == nil {
|
|
|
|
m.checkAndRemoveCache()
|
|
|
|
}
|
|
|
|
}()
|
2020-04-08 21:26:14 +08:00
|
|
|
var (
|
2020-10-20 21:01:39 +08:00
|
|
|
fieldNameDelete = m.getSoftFieldNameDeleted()
|
2020-11-10 10:37:42 +08:00
|
|
|
conditionWhere, conditionExtra, conditionArgs = m.formatCondition(false, false)
|
2020-04-08 21:26:14 +08:00
|
|
|
)
|
|
|
|
// Soft deleting.
|
2020-04-09 22:48:21 +08:00
|
|
|
if !m.unscoped && fieldNameDelete != "" {
|
2020-04-08 21:26:14 +08:00
|
|
|
return m.db.DoUpdate(
|
|
|
|
m.getLink(true),
|
|
|
|
m.tables,
|
2020-06-17 23:47:47 +08:00
|
|
|
fmt.Sprintf(`%s=?`, m.db.QuoteString(fieldNameDelete)),
|
2020-04-08 21:26:14 +08:00
|
|
|
conditionWhere+conditionExtra,
|
2020-06-17 23:47:47 +08:00
|
|
|
append([]interface{}{gtime.Now().String()}, conditionArgs...),
|
2020-04-08 21:26:14 +08:00
|
|
|
)
|
|
|
|
}
|
2020-11-06 00:00:41 +08:00
|
|
|
conditionStr := conditionWhere + conditionExtra
|
|
|
|
if !gstr.ContainsI(conditionStr, " WHERE ") {
|
|
|
|
return nil, gerror.New("there should be WHERE condition statement for DELETE operation")
|
|
|
|
}
|
|
|
|
return m.db.DoDelete(m.getLink(true), m.tables, conditionStr, conditionArgs...)
|
2020-03-13 17:21:30 +08:00
|
|
|
}
|