刪除一條記錄時(shí),刪除對(duì)象需要指定主鍵,否則會(huì)觸發(fā)批量Delete,例如:
// Email 的 ID 是 `10`
db.Delete(&email)
// DELETE from emails where id = 10;
// 帶額外條件的刪除
db.Where("name = ?", "張三").Delete(&email)
// DELETE from emails where id = 10 AND name = "張三";
GORM允許通過(guò)主鍵(可以是復(fù)合主鍵)和內(nèi)聯(lián)條件來(lái)刪除對(duì)象,它可以使用數(shù)字,如以下例子
db.Delete(&User{}, 10)
// DELETE FROM users WHERE id = 10;
db.Delete(&User{}, "10")
// DELETE FROM users WHERE id = 10;
db.Delete(&users, []int{1,2,3})
// DELETE FROM users WHERE id IN (1,2,3);
如果指定的值不包括主屬性,那么 GORM 會(huì)執(zhí)行批量刪除,它將刪除所有匹配的記錄
db.Where("email LIKE ?", "%張三%").Delete(&Email{})
// DELETE from emails where email LIKE "%張三%";
db.Delete(&Email{}, "email LIKE ?", "%張三%")
// DELETE from emails where email LIKE "%張三%";
如果你的模型包含了一個(gè)gorm.deletedat字段(gorm.Model 已經(jīng)包含了該字段),它將自動(dòng)獲得軟刪除的能力!擁有軟刪除能力的模型調(diào)用Delete時(shí),記錄不會(huì)被數(shù)據(jù)庫(kù)刪除。但GORM會(huì)將DeletedAt置為當(dāng)前時(shí)間, 并且你不能再通過(guò)普通的查詢(xún)方法找到該記錄。
// user 的 ID 是 `111`
db.Delete(&user)
// UPDATE users SET deleted_at="2022-03-04 10:16" WHERE id = 111;
// 批量刪除
db.Where("age = ?", 20).Delete(&User{})
// UPDATE users SET deleted_at="2022-03-04 10:16" WHERE age = 20;
// 在查詢(xún)時(shí)會(huì)忽略被軟刪除的記錄
db.Where("age = 20").Find(&user)
// SELECT * FROM users WHERE age = 20 AND deleted_at IS NULL;
如果你不想引入gorm.Model,你也可以這樣啟用軟刪除特性
type User struct {
ID int
Deleted gorm.DeletedAt
Name string
}
更多建議: