删除只有一个操作,delete。也是先找到再去删除。 可以删除单条记录,也可以删除多条记录。
var s Student
db.Debug().Delete(&s, "age = ?", 100)
fmt.Println(s)
[15.878ms] [rows:1] DELETE FROM `student` WHERE age = 100
var s Student
db.Debug().Take(&s, "age = ?", 101)
db.Debug().Delete(&s)
[2.060ms] [rows:1] SELECT * FROM `student` WHERE age = 101 LIMIT 1
[4.494ms] [rows:1] DELETE FROM `student` WHERE `student`.`id` = 1
删除
警告:删除记录时,需要确保其主要字段具有值,GORM将使用主键删除记录,如果主要字段为空,GORM将删除模型的所有记录
// 删除存在的记录
db.Delete(&email)
DELETE from emails where id=10;
// 为Delete语句添加额外的SQL选项
db.Set("gorm:delete_option", "OPTION (OPTIMIZE FOR UNKNOWN)").Delete(&email)
DELETE from emails where id=10 OPTION (OPTIMIZE FOR UNKNOWN);
批量删除
删除所有匹配记录
db.Where("email LIKE ?", "%jinzhu%").Delete(Email{})
DELETE from emails where email LIKE "%jinhu%";
db.Delete(Email{}, "email LIKE ?", "%jinzhu%")
DELETE from emails where email LIKE "%jinhu%";