When a struct has DeletedAt field, I thought gorm works as follows.
db.Unscoped().Where("age = ?", 20).Delete(&User{})
////DELETE from users where age = 20;
However, gorm actually works as follows.
db.Unscoped().Where("age = ?", 20).Delete(&User{})
//// UPDATE users SET deleted_at="2013-10-29 10:23" WHERE age = 20;
Is this an expected behavior?
Hi uzimith,
Yes, this is expected behaviour that takes advantage of Gorm's "Soft Delete" feature. Records that have been soft-deleted are ignored when Gorm queries for related records.
You can use Unscoped to hard-delete a record, instead of soft-deleting it.
Thank you, enmand.
You can use Unscoped to hard-delete a record, instead of soft-deleting it.
Does this mean I should use as follows?
db.Unscoped().Delete(&order)
//// DELETE FROM orders WHERE id=10;
OK, I understood it.
However, I'm wondering if gorm doesn't have batch hard delete.
Hi @uzimith
this is hard batch delete?
db.Unscoped().Where("age = ?", 20).Delete(&User{})
////DELETE from users where age = 20;
Hi jinzhu,
I tried writing simple sample code and it worked well.
I might misunderstand a behavior. Sorry.
How to get back that value I mean how to the field DeletedAt to null again?
@Asad-noor I faced the same question, and I found a solution that is using SetColumn in BeforeUpdate/BeforeSave callback.
func (u *Users) BeforeUpdate(scope *gorm.Scope) {
scope.SetColumn("deleted_at", nil)
}
Most helpful comment
Hi @uzimith
this is hard batch delete?