type User struct { ID uint Name string`gorm:"uniqueIndex:udx_name"` DeletedAt soft_delete.DeletedAt `gorm:"uniqueIndex:udx_name"` }
Unix 时间戳
使用unix时间戳作为删除标志
1 2 3 4 5 6 7 8 9 10 11 12 13
import"gorm.io/plugin/soft_delete"
type User struct { ID uint Name string DeletedAt soft_delete.DeletedAt }
// 查询 SELECT * FROM users WHERE deleted_at = 0;
// 软删除 UPDATE users SET deleted_at = /* current unix second */ WHERE ID = 1;
你同样可以指定使用毫秒 milli或纳秒 nano作为值,如下例:
1 2 3 4 5 6 7 8 9 10 11 12
type User struct { ID uint Name string DeletedAt soft_delete.DeletedAt `gorm:"softDelete:milli"` // DeletedAt soft_delete.DeletedAt `gorm:"softDelete:nano"` }
// 查询 SELECT * FROM users WHERE deleted_at = 0;
// 软删除 UPDATE users SET deleted_at = /* current unix milli second or nano second */ WHERE ID = 1;
使用 1 / 0 作为 删除标志
1 2 3 4 5 6 7 8 9 10 11 12 13
import"gorm.io/plugin/soft_delete"
type User struct { ID uint Name string IsDel soft_delete.DeletedAt `gorm:"softDelete:flag"` }
// 查询 SELECT * FROM users WHERE is_del = 0;
// 软删除 UPDATE users SET is_del = 1 WHERE ID = 1;
混合模式
混合模式可以使用 0,1或者unix时间戳来标记数据是否被软删除,并同时可以保存被删除时间
1 2 3 4 5 6 7 8 9 10 11 12 13 14
type User struct { ID uint Name string DeletedAt time.Time IsDel soft_delete.DeletedAt `gorm:"softDelete:flag,DeletedAtField:DeletedAt"`// use `1` `0` // IsDel soft_delete.DeletedAt `gorm:"softDelete:,DeletedAtField:DeletedAt"` // use `unix second` // IsDel soft_delete.DeletedAt `gorm:"softDelete:nano,DeletedAtField:DeletedAt"` // use `unix nano second` }
// 查询 SELECT * FROM users WHERE is_del = 0;
// 软删除 UPDATE users SET is_del = 1, deleted_at = /* current unix second */ WHERE ID = 1;