Home > Software engineering >  How can I restore data that I soft deleted with gorm deletedAt
How can I restore data that I soft deleted with gorm deletedAt

Time:10-07

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

CodePudding user response:

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).

CodePudding user response:

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
  • Related