GORM—物理删除,软删除

作者: adm 分类: go 发布时间: 2022-09-25

如果有DeletedAt *time.Time sql:”index”,其实是软删除

删除记录
删除记录时,请确保主键字段有值,GORM 会通过主键去删除记录,如果主键为空,GORM 会删除该 model 的所有记录。

	// 删除现有记录
	db.Delete(&email)
	// DELETE from emails where id=10;
	
	// 为删除 SQL 添加额外的 SQL 操作
	db.Set("gorm:delete_option", "OPTION (OPTIMIZE FOR UNKNOWN)").Delete(&email)
	// DELETE from emails where id=10 OPTION (OPTIMIZE FOR UNKNOWN);

批量删除
删除全部匹配的记录

	// DELETE from emails where email LIKE "%wxf%";
	db.Where("email LIKE ?", "%wxf%").Delete(Email{})
	// DELETE from emails where email LIKE "%wxf%";
	db.Delete(Email{}, "email LIKE ?", "%wxf%")

软删除
如果一个 model 有 DeletedAt 字段,他将自动获得软删除的功能! 当调用 Delete 方法时, 记录不会真正的从数据库中被删除, 只会将DeletedAt 字段的值会被设置为当前时间

	// UPDATE users SET deleted_at="2013-10-29 10:23" WHERE id = 111;
	db.Delete(&user)

	// 批量删除
	// UPDATE users SET deleted_at="2013-10-29 10:23" WHERE age = 20;
	db.Where("age = ?", 20).Delete(&User{})

	// 查询记录时会忽略被软删除的记录
	// SELECT * FROM users WHERE age = 20 AND deleted_at IS NULL;
	db.Where("age = 20").Find(&user)

	// Unscoped 方法可以查询被软删除的记录
	// SELECT * FROM users WHERE age = 20;
	db.Unscoped().Where("age = 20").Find(&users)

物理删除

	// Unscoped 方法可以物理删除记录
	// DELETE FROM orders WHERE id=10;
	db.Unscoped().Delete(&order)
	// DELETE FROM orders WHERE id=10 and age = 20;
	db.Unscoped().Where("age = 20").Delete(&order)

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!