How can I restore data that I soft deleted with gorm deletedAt

huangapple go评论78阅读模式
英文:

How can I restore data that I soft deleted with gorm deletedAt

问题

目前正在使用gorm,我软删除了一条数据。
我知道如何获取已软删除的数据。
但是我需要恢复它,如果有人知道如何做,请告诉我。

英文:

Currently using gorm and I soft deleted one data
I know how to get data that its soft deleted
But I need to restore it so if anyone know how to do it please let me know

答案1

得分: 4

你可以将deleted_at列更新为NULL,例如:

db.Model(&User{}).Where("id", 1).Update("deleted_at", nil)

示例:

type User struct {
    gorm.Model
    gorm.DeletedAt
    Name string
}

db.AutoMigrate(&User{})
db.Create(&User{Name: "John Doe"})

u := new(User)
fmt.Println(db.First(u, 1).Error) // nil
db.Delete(u, 1)
fmt.Println(db.First(u, 1).Error) // 记录未找到
db.Model(u).Update("deleted_at", nil)
fmt.Println(db.First(u, 1).Error) // nil
英文:

https://gorm.io/docs/update.html#Update-single-column

You can update the deleted_at column to NULL, e.g.

db.Model(&User{}).Where("id", 1).Update("deleted_at", nil)

Example:

type User struct {
	gorm.Model
	gorm.DeletedAt
	Name string
}

db.AutoMigrate(&User{})
db.Create(&User{Name: "John Doe"})

u := new(User)
fmt.Println(db.First(u, 1).Error) // nil
db.Delete(u, 1)
fmt.Println(db.First(u, 1).Error) // record not found
db.Model(u).Update("deleted_at", nil)
fmt.Println(db.First(u, 1).Error) // nil

答案2

得分: 2

检查一下在问题4388中提到的未删除是否有帮助:

model.DeletedAt = gorm.DeletedAt{}
if err := o.DbPointer.Table(table).Save(&model).Error; err != nil {
	return err
}

尽管在自定义联接表中重新插入软删除的关系似乎不明显(或者不起作用)。

英文:

Check if an undelete, mentioned in issue 4388 would help:

model.DeletedAt = gorm.DeletedAt{}
if err := o.DbPointer.Table(table).Save(&model).Error; err != nil {
	return err
}

Although re-inserting soft-deleted relation in a custom join table does not seem obvious (or working).

答案3

得分: 2

使用最新的GORM版本,需要使用Unscoped()方法来激活软删除的记录。

db.Unscoped().Model(&model{}).Where("id", id).Update("deleted_at", nil)

这段代码的作用是取消作用域限制,然后更新指定id的记录的deleted_at字段为nil,从而激活软删除的记录。

英文:

With the latest GORM version, need to unscoped it to activate the soft deleted records.

db.Unscoped().Model(&model{}).Where("id", id).Update("deleted_at", nil)

huangapple
  • 本文由 发表于 2021年10月7日 13:17:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/69475802.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定