github.com/gogf/gf@v1.16.9/database/gdb/gdb_model_delete.go (about)

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