乐闻世界logo
搜索文章和话题

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

1个答案

1

To restore data that has been soft-deleted using GORM's deletedAt field, you can follow these steps:

  1. Querying Soft-Deleted Data: By default, GORM query operations automatically ignore soft-deleted records (i.e., those where the deletedAt field is not null). To retrieve these records, you must use the Unscoped method to fetch all data, including soft-deleted entries.

    go
    var user User db.Unscoped().Where("id = ?", userID).Find(&user)

    Here, User is the model name, and userID is the ID of the record you intend to restore.

  2. Restoring the Data: Set the deletedAt field of the retrieved record to null to restore it and make it visible again.

    go
    db.Model(&user).Update("deletedAt", nil)

    This updates the deletedAt field 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:

go
package 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.

2024年8月12日 17:20 回复

你的答案