Delete a Record
When deleting a record, the deleted value needs to have primary key or it will trigger a Batch Delete, for example:
// Email's ID is `10` |
Delete with primary key
GORM allows to delete objects using primary key(s) with inline condition, it works with numbers, check out Query Inline Conditions for details
db.Delete(&User{}, 10) |
Delete Hooks
GORM allows hooks BeforeDelete
, AfterDelete
, those methods will be called when deleting a record, refer Hooks for details
func (u *User) BeforeDelete(tx *gorm.DB) (err error) { |
Batch Delete
The specified value has no primary value, GORM will perform a batch delete, it will delete all matched records
db.Where("email LIKE ?", "%jinzhu%").Delete(&Email{}) |
Block Global Delete
If you perform a batch delete without any conditions, GORM WON’T run it, and will return ErrMissingWhereClause
error
You have to use some conditions or use raw SQL or enable AllowGlobalUpdate
mode, for example:
db.Delete(&User{}).Error // gorm.ErrMissingWhereClause |
Returning Data From Deleted Rows
Return deleted data, only works for database support Returning, for example:
// return all columns |
Soft Delete
If your model includes a gorm.DeletedAt
field (which is included in gorm.Model
), it will get soft delete ability automatically!
When calling Delete
, the record WON’T be removed from the database, but GORM will set the DeletedAt
‘s value to the current time, and the data is not findable with normal Query methods anymore.
// user's ID is `111` |
If you don’t want to include gorm.Model
, you can enable the soft delete feature like:
type User struct { |
Find soft deleted records
You can find soft deleted records with Unscoped
db.Unscoped().Where("age = 20").Find(&users) |
Delete permanently
You can delete matched records permanently with Unscoped
db.Unscoped().Delete(&order) |
Delete Flag
Use unix second as delete flag
import "gorm.io/plugin/soft_delete" |
INFO when using unique field with soft delete, you should create a composite index with the unix second based
DeletedAt
field, e.g:
import "gorm.io/plugin/soft_delete"
type User struct {
ID uint
Name string `gorm:"uniqueIndex:udx_name"`
DeletedAt soft_delete.DeletedAt `gorm:"uniqueIndex:udx_name"`
}
Use 1
/ 0
as delete flag
import "gorm.io/plugin/soft_delete" |