Gorm 删除

删除一条记录

删除一条记录时,删除对象需要指定主键,否则会触发 批量 Delete,例如:

db.Debug().Where("id = ?", 6).Delete(new(User))
// DELETE FROM `users` WHERE id = 6

db.Debug().Delete(User{}, 5)
// DELETE FROM `users` WHERE `users`.`id` = 5

根据主键删除

GORM 允许通过主键(可以是复合主键)和内联条件来删除对象

// 根据主键删除一个或多个
db.Debug().Delete(&User{}, []int{11, 12})
// DELETE FROM `users` WHERE `users`.`id` IN (11, 12)

Delete Hook

对于删除操作,GORM 支持 BeforeDelete、AfterDelete Hook,在删除记录时会调用这些方法

func (u *User) BeforeDelete(tx *gorm.DB) (err error) {
        fmt.Println("User BeforeDelete执行了")
        return
}
func (u *User) AfterDelete(tx *gorm.DB) (err error) {
        fmt.Println("User AfterDelete执行了")
        return
}

批量删除

如果指定的值不包括主属性,那么 GORM 会执行批量删除,它将删除所有匹配的记录

db.Debug().Where("name = ?", "dawang").Delete(&User{})
// DELETE FROM `users` WHERE name = 'dawang'

db.Debug().Delete(new(User), "name LIKE ?", "%wang%")
// DELETE FROM `users` WHERE name LIKE '%wang%'

阻止全局删除

db.Delete(&User{}).Error // WHERE conditions required

db.Where("1 = 1").Delete(&User{})
// DELETE FROM `users` WHERE 1=1

db.Exec("DELETE FROM users")
// DELETE FROM users

db.Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(&User{})
// DELETE FROM users

软删除

db.Debug().Delete(new(User), 21)
// UPDATE `users` SET `deleted_at`='2021-11-22 15:25:02.646' WHERE `users`.`id` = 23 AND `users`.`deleted_at` IS NULLvar user User
db.First(&user, 21)
fmt.Println(user)
// SELECT * FROM `users` WHERE `users`.`id` = 23 AND `users`.`deleted_at` IS NULL ORDER BY `users`.`id` LIMIT 1

查找软删除记录

查找具有非范围的软删除记录

db.Debug().Unscoped().First(&user, 21)
// SELECT * FROM `users` WHERE `users`.`id` = 21 ORDER BY `users`.`id` LIMIT 1

永久删除

db.Debug().Unscoped().Delete(&User{}, 20)
// DELETE FROM `users` WHERE `users`.`id` = 20