To restore data that has been soft-deleted using GORM's deletedAt field, you can follow these steps:
-
Querying Soft-Deleted Data: By default, GORM query operations automatically ignore soft-deleted records (i.e., those where the
deletedAtfield is not null). To retrieve these records, you must use theUnscopedmethod to fetch all data, including soft-deleted entries.govar user User db.Unscoped().Where("id = ?", userID).Find(&user)Here,
Useris the model name, anduserIDis the ID of the record you intend to restore. -
Restoring the Data: Set the
deletedAtfield of the retrieved record to null to restore it and make it visible again.godb.Model(&user).Update("deletedAt", nil)This updates the
deletedAtfield to null, indicating the data is no longer soft-deleted.
Example:
Suppose you have a user management system where the User model implements GORM's soft-delete functionality. To restore the user with ID 123, use the following code example:
gopackage main import ( "gorm.io/gorm" "gorm.io/driver/sqlite" "time" ) type User struct { gorm.Model Name string } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("Database connection failed") } var user User // Query soft-deleted data db.Unscoped().Where("id = ?", 123).Find(&user) if user.ID != 0 { // Restore data db.Model(&user).Update("DeletedAt", nil) println("User data has been restored") } else { println("User not found") } }
In this example, Unscoped is used with the specified ID to locate the soft-deleted user record, and Update sets DeletedAt to null to restore it.
By following this approach, you can flexibly restore any soft-deleted data and integrate this process seamlessly with your business logic.