Gorm: Don't gorm physical delete when struct has DeletedAt field and you use Unscoped?

Created on 16 Jan 2015  路  6Comments  路  Source: go-gorm/gorm

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?

Most helpful comment

Hi @uzimith

this is hard batch delete?

db.Unscoped().Where("age = ?", 20).Delete(&User{})
////DELETE from users where age = 20;

All 6 comments

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)

}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

alanyuen picture alanyuen  路  3Comments

hypertornado picture hypertornado  路  3Comments

fieryorc picture fieryorc  路  3Comments

Quentin-M picture Quentin-M  路  3Comments

satb picture satb  路  3Comments