
我正在使用 GORM V1。我有一个要求,我们想要添加一个类似于 GORM deleted_at 的 archived_at 列。实体可以存档和取消存档,默认情况下我们希望使用 archived_at 为 NULL 来查询记录。
我目前的想法是利用 GORM 回调来注册回调
这听起来不错,但我如何有效地复制相当于存档的 Unscoped() 。
archived_at 列是否应添加到必要的回调中?archived_at IS NOT NULL)。编辑 - 我的用例是同时使用 deleted_at 和 archived_at 字段,而不是使用一个字段代替另一个字段。我想保留软删除的能力,同时添加归档实体的能力。用户可能只是被存档,然后可能被删除(软删除)。
立即学习“go语言免费学习笔记(深入)”;
修正说明:1,实现真正的软件开源。2,安装界面的美化3,真正实现栏目的递归无限极分类。4,后台添加幻灯片图片的管理,包括添加,修改,删除等。5,修正添加新闻的报错信息6,修正网站参数的logo上传问题7,修正产品图片的栏目无限极分类8,修正投票系统的只能单选问题9,添加生成静态页功能10,添加缓存功能特点和优势1. 基于B/S架构,通过本地电脑、局域网、互联网皆可使用,使得企业的管理与业务不受地域
0
邀请反馈。这是我目前想到的。
回调.go
package db
import (
"fmt"
"reflect"
"gorm.io/gorm"
)
const (
gormsettingkeyunscopearchive = "unscope_archive"
structfieldnamearchivedat = "archivedat"
)
// archivedquerycallback - conditionally adds "where archived_at is null" if the model being queried has the following
// 1. struct field represented by structfieldnamearchivedat
// 2. gorm instance setting gormsettingkeyunscopearchive, see unscopearchive
func archivedquerycallback(db *gorm.db) {
// check if model is a pointer and has an indirect struct type
if db.statement.model != nil &&
reflect.typeof(db.statement.model).kind() == reflect.ptr &&
reflect.indirect(reflect.valueof(db.statement.model)).kind() == reflect.struct {
stmt := &gorm.statement{db: db}
parseerr := stmt.parse(db.statement.model)
if parseerr != nil {
panic(parseerr)
}
if _, archivedatexists := stmt.schema.fieldsbyname[structfieldnamearchivedat]; archivedatexists {
v, ok := db.instanceget(gormsettingkeyunscopearchive)
if ok {
if v == true {
return
}
}
db.where(fmt.sprintf("%s is null", stmt.schema.fieldsbyname[structfieldnamearchivedat].dbname))
}
}
}
范围.go
// unscopearchive - sets a true value for the key gormsettingkeyunscopearchive
func unscopearchive(db *gorm.db) *gorm.db {
db = db.instanceset(gormsettingkeyunscopearchive, true)
return db
}
main.go
type User {
ID string `gorm:"primary_key" json:"id" valid:"uuidv4, optional"`
CreatedAt time.Time `valid:"-" json:"created_at"`
UpdatedAt time.Time `valid:"-" json:"-"`
DeletedAt gorm.DeletedAt `sql:"index" valid:"-" json:"-"`
ArchivedAt time.Time
}
var user []User
ctx := context.Background()
dbClient := InitializeGORM() //helper
_ := dbClient.WithContext(ctx).Find(&user).Error // SELECT * FROM users WHERE deleted_at IS NULL AND archived_at IS NULL;
_ := dbClient.WithContext(ctx).Scopes(UnscopeArchive).Find(&user).Error // SELECT * FROM users WHERE deleted_at IS NULL;
以上就是Golang GORM 实现类似于软删除的archived_at的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号