lilorox
lilorox

Reputation: 165

Retrieve deleted rows on deletion

Is there a way to retrieve the rows deleted when calling Delete()?

I'd like to avoid using 'SELECT ... FOR UPDATE' to first get the list of rows I'm deleting.

type MyModel struct {
  gorm.Model
  ....
}

res := db.Where("updated_at < ?", expirationDate).
    Set("gorm:save_associations", false).
    Delete(&MyModel{})

I noticed there is a res.Value attribute but it seems to be the empty struct I pass as argument of Delete().

Upvotes: 4

Views: 3679

Answers (1)

edkeveked
edkeveked

Reputation: 18381

Your query should be this way instead. db.Where does not return the struct. It modifies the pointer passed as parameter.

var res MyModel{}

db.Where("updated_at < ?", expirationDate).
    Delete(&res)

Upvotes: 1

Related Questions