sdbc/delete_scope.go
2023-09-17 11:14:12 +08:00

61 lines
1.2 KiB
Go

package sdbc
import (
"context"
"gorm.io/gorm"
)
type _delete struct {
scope *scope
sdbc *Driver
ctx context.Context
where []any
isHard bool
}
// SetWhere 设置删除条件
func (d *_delete) SetWhere(query any, args ...any) *_delete {
d.where = append(d.where, query)
d.where = append(d.where, args...)
return d
}
// SetHardDelete 设置硬删除删除
func (d *_delete) SetHardDelete(hard bool) *_delete {
d.isHard = hard
return d
}
// DeleteByID 通过主键删除记录
func (d *_delete) DeleteByID(id any) error {
db := d.sdbc.client
if d.isHard {
db = db.Unscoped()
}
return db.Delete(d.scope.model.ptr(), id).Error
}
// Delete 基于条件做删除 无条件删除使用 MustDelete
func (d *_delete) Delete() error {
db := d.sdbc.client
if d.isHard {
db = db.Unscoped()
}
if len(d.where) != 0 {
db = db.Where(d.where[0], d.where[1:]...)
}
return db.Delete(d.scope.model.ptr()).Error
}
// MustDelete 基于条件做删除 无条件则全部删除
func (d *_delete) MustDelete() error {
db := d.sdbc.client
if d.isHard {
db = db.Unscoped()
}
if len(d.where) != 0 {
db = db.Where(d.where[0], d.where[1:]...)
}
return db.Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(d.scope.model.ptr()).Error
}