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

Viewed 2079

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

3 Answers

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

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