[gorm] beforeUpdate hook 方法

2021-06-15 10:26:04 +08:00
 bigNewsMaker

gorm 中 BeforeUpdate 方法能取到 update 之后的值吗,或者使用 gorm 如何实现这种 hook ?

func (m *User) BeforeUpdate(tx *gorm.DB) (err error) {
	if tx.Statement.Changed("Mobile") {
		err = tx.Model(&Profile{}).Where("user_id = ?",m.ID).Update("mobile", m.Mobile(这里是更新之前的 mobile)).Error
		if err != nil {
			DB.Error("user before update hook(mobile) error", zap.Any("err", err))
		}
	}
    }

如上面的代码,只能按照文档里的说明,只能用 changed 来检测 col 是否被更改, 但是拿不到更新后的值。或者是上面的这种实现方法对么,求指点 问:如何实现这种在检测到值更改之后,然后用 更新后的值 再去做操作的 hook ?

1303 次点击
所在节点    Go 编程语言
2 条回复
chengxiao
2021-06-15 11:08:26 +08:00
更新后的值 不是用 AfterUpdate?
bigNewsMaker
2021-06-15 11:33:55 +08:00
@chengxiao AfterUpdate 的确是有个 AfterUpdate 的 hook,但是 AfterUpdate 里的 statement.Changed 方法不能检测到 col 是否更改,所以,一直返回的 false,不能进入 if 里面的逻辑。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/783426

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX