【发布时间】:2021-02-19 00:05:34
【问题描述】:
在尝试使用 golang 中的 gorm 插入日志以检测模型的值更改时,我正在使用插件:
type MyModel struct {
Id
Name
}
type Log struct {
Id
NewValue
OldValue
CreatedAt
}
我的插件定义是这样的:
func ChangelogCreatePlugin(db *gorm.DB) {
log := &Log{NewValue: "the new value", OldValue: "the old value", CreatedAt: "current time"}
// Here is the problem
db.Save(log) <- this is not acceptable
}
在插件中使用 db *gorm.DB 参数插入不同的数据模型是不可接受的,因为该参数已初始化为接受来自触发插件的同一模型的数据。
我的要求是将我的日志存储在同一个数据库事务中,因此如果其中一个失败,它们都应该失败。如何在gorm中做这样的事情?
我知道钩子。钩子在我的情况下没有用,因为我希望我的日志跟踪不同的模型,所以我正在寻找更多“可重用”的解决方案,而不是在我的模型中复制/粘贴钩子实现。
【问题讨论】:
标签: go transactions go-gorm