If your model includes a gorm.DeletedAt field (which is included in gorm.Model), information technology volition get soft delete ability automatically!
When calling Delete, the record WON'T exist removed from the database, merely GORM will set up the DeletedAt'southward value to the current fourth dimension, and the data is not findable with normal Query methods anymore.
db.Delete(&user)
db.Where("age = ?", 20).Delete(&User{})
db.Where("age = 20").Observe(&user)
If y'all don't want to include gorm.Model, you can enable the soft delete feature similar:
type User struct { ID int Deleted gorm.DeletedAt Name string }
Find soft deleted records
Y'all can find soft deleted records with Unscoped
db.Unscoped().Where("historic period = 20").Find(&users)
Delete permanently
You tin can delete matched records permanently with Unscoped
db.Unscoped().Delete(&guild)
Delete Flag
Use unix second as delete flag
import"gorm.io/plugin/soft_delete"
type User struct { ID uint Proper noun string DeletedAt soft_delete.DeletedAt }
SELECT * FROM users WHERE deleted_at = 0;
UPDATE users SET deleted_at = WHERE ID = ane;
INFO when using unique field with soft delete, you should create a composite index with the unix second based DeletedAt field, e.thousand:
import"gorm.io/plugin/soft_delete"
type User struct { ID uint Proper noun cord`gorm:"uniqueIndex:udx_name"` DeletedAt soft_delete.DeletedAt `gorm:"uniqueIndex:udx_name"` }
Use one / 0 as delete flag
import"gorm.io/plugin/soft_delete"
type User struct { ID uint Proper noun string IsDel soft_delete.DeletedAt `gorm:"softDelete:flag"` }
0 Response to "Does Primary Key Automatically Update If You Delete A Row"
Post a Comment