golang gorm delete

If a bulk delete is performed without any conditions, GORM does not perform the operation and returns an ErrMissingWhereClause error

For this, you have to add some conditions, or use native SQL, or enable AllowGlobalUpdate mode, for example:

db.Delete(&User{}).Error // gorm.ErrMissingWhereClause
db.Where("1 = 1").Delete(&User{})
// DELETE FROM `users` WHERE 1=1
db.Exec("DELETE FROM users")
// DELETE FROM users
db.Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(&User{})
// DELETE FROM users

soft delete

If your model includes a gorm.DeletedAt field (which is already included in gorm.Model), it will automatically gain the ability to soft delete!

When a model with soft delete capability calls Delete, the record is not actually deleted from the database. But GORM will set DeletedAt to the current time, and you can no longer find the record through normal query methods.

// user's ID is `111`
// UPDATE users SET deleted_at="2013-10-29 10:23" WHERE id = 111;
// batch deletion
db.Where("age = ?", 20).Delete(&User{})
// UPDATE users SET deleted_at="2013-10-29 10:23" WHERE age = 20;
// Soft deleted records are ignored when querying
db.Where("age = 20").Find(&user)
// SELECT * FROM users WHERE age = 20 AND deleted_at IS NULL;

If you don’t want to import gorm.Model, you can also enable the soft delete feature like this:

db.Unscoped().Where("age = 20").Find(&users)
// SELECT * FROM users WHERE age = 20;

Leave a Reply

Your email address will not be published.