// Delete by ID err := gorm.G[Email](db).Where("id = ?", 10).Delete(ctx) // DELETE from emails where id = 10;
// Delete with additional conditions err := gorm.G[Email](db).Where("id = ? AND name = ?", 10, "jinzhu").Delete(ctx) // DELETE from emails where id = 10 AND name = "jinzhu";
Traditional API
// Email 的 ID 是 `10` db.Delete(&email) // DELETE from emails where id = 10;
// 带额外条件的删除 db.Where("name = ?", "jinzhu").Delete(&email) // DELETE from emails where id = 10 AND name = "jinzhu";
func(u *User) BeforeDelete(tx *gorm.DB) (err error) { if u.Role == "admin" { return errors.New("admin user not allowed to delete") } return }
批量删除
如果指定的值不包括主属性,那么 GORM 会执行批量删除,它将删除所有匹配的记录
Generics API
ctx := context.Background()
// Batch delete with conditions err := gorm.G[Email](db).Where("email LIKE ?", "%jinzhu%").Delete(ctx) // DELETE from emails where email LIKE "%jinzhu%";
Traditional API
db.Where("email LIKE ?", "%jinzhu%").Delete(&Email{}) // DELETE from emails where email LIKE "%jinzhu%";
db.Delete(&Email{}, "email LIKE ?", "%jinzhu%") // DELETE from emails where email LIKE "%jinzhu%";
可以将一个主键切片传递给Delete 方法,以便更高效的删除数据量大的记录
var users = []User{{ID: 1}, {ID: 2}, {ID: 3}} db.Delete(&users) // DELETE FROM users WHERE id IN (1,2,3);
db.Delete(&users, "name LIKE ?", "%jinzhu%") // DELETE FROM users WHERE name LIKE "%jinzhu%" AND id IN (1,2,3);
type User struct { ID uint Name string`gorm:"uniqueIndex:udx_name"` DeletedAt soft_delete.DeletedAt `gorm:"uniqueIndex:udx_name"` }
Unix 时间戳
使用unix时间戳作为删除标志
import"gorm.io/plugin/soft_delete"
type User struct { ID uint Name string DeletedAt soft_delete.DeletedAt }
// 查询 SELECT * FROM users WHERE deleted_at = 0;
// 软删除 UPDATE users SET deleted_at = /* current unix second */ WHERE ID = 1;
你同样可以指定使用毫秒 milli或纳秒 nano作为值,如下例:
type User struct { ID uint Name string DeletedAt soft_delete.DeletedAt `gorm:"softDelete:milli"` // DeletedAt soft_delete.DeletedAt `gorm:"softDelete:nano"` }
// 查询 SELECT * FROM users WHERE deleted_at = 0;
// 软删除 UPDATE users SET deleted_at = /* current unix milli second or nano second */ WHERE ID = 1;
使用 1 / 0 作为 删除标志
import"gorm.io/plugin/soft_delete"
type User struct { ID uint Name string IsDel soft_delete.DeletedAt `gorm:"softDelete:flag"` }
// 查询 SELECT * FROM users WHERE is_del = 0;
// 软删除 UPDATE users SET is_del = 1 WHERE ID = 1;
混合模式
混合模式可以使用 0,1或者unix时间戳来标记数据是否被软删除,并同时可以保存被删除时间
type User struct { ID uint Name string DeletedAt time.Time IsDel soft_delete.DeletedAt `gorm:"softDelete:flag,DeletedAtField:DeletedAt"`// use `1` `0` // IsDel soft_delete.DeletedAt `gorm:"softDelete:,DeletedAtField:DeletedAt"` // use `unix second` // IsDel soft_delete.DeletedAt `gorm:"softDelete:nano,DeletedAtField:DeletedAt"` // use `unix nano second` }
// 查询 SELECT * FROM users WHERE is_del = 0;
// 软删除 UPDATE users SET is_del = 1, deleted_at = /* current unix second */ WHERE ID = 1;