3

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
lilorox
  • 155
  • 2
  • 12
  • 4
    gorm does not do it due to spotty db support for this. You'll need to execute a raw sql statement such as `DELETE .... RETURNING ....` on postgres. I think mysql doesn't have that though, but you didn't specify which database it's for. – Marc Feb 05 '18 at 15:04

1 Answers1

1

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)
edkeveked
  • 17,989
  • 10
  • 55
  • 93