背景
当tableStruct
内部有gorm.Model
时,默认的查询语句都会包含 deleted_at IS NULL 的判断,如何不限制这个条件呢?
原理分析
gorm.Model 是一个包含一些基本字段的结构体, 包含的字段有 ID,CreatedAt, UpdatedAt, DeletedAt
解决方法
1.
Unscoped
方法
model.Db.Debug().Unscoped().Where(map[string]interface{}{"id": id}).Find(&variable)
2. 使用原始查询
model.Db.Raw("SELECT * FROM table LIMIT 1").Scan(&variable)
3. 自定义struct不跟 gorm.Model 结合
总结
Debug可以记录sql的详细执行过程
Unscoped 方法设置tx.Statement.Unscoped为true,针对软删除会追加SoftDeleteDeleteClause,即设置deleted_at为指定的时间戳;而callbacks的Delete方法在db.Statement.Unscoped为false的时候才追加db.Statement.Schema.DeleteClauses,而Unscoped则执行的是物理删除。
更多scope用法参考:https://www.phpmianshi.com/?id=385
- 本文固定链接: https://www.phpmianshi.com/?id=4089
- 转载请注明: admin 于 PHP面试网 发表
《本文》有 0 条评论