The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
bigNewsMaker

[gorm] beforeUpdate hook 方法

  •  
  •   bigNewsMaker · Jun 15, 2021 · 2145 views
    This topic created in 1802 days ago, the information mentioned may be changed or developed.

    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 ?

    2 replies    2021-06-15 11:33:55 +08:00
    chengxiao
        1
    chengxiao  
       Jun 15, 2021
    更新后的值 不是用 AfterUpdate?
    bigNewsMaker
        2
    bigNewsMaker  
    OP
       Jun 15, 2021
    @chengxiao AfterUpdate 的确是有个 AfterUpdate 的 hook,但是 AfterUpdate 里的 statement.Changed 方法不能检测到 col 是否更改,所以,一直返回的 false,不能进入 if 里面的逻辑。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2575 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 15:58 · PVG 23:58 · LAX 08:58 · JFK 11:58
    ♥ Do have faith in what you're doing.