V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
swxc
V2EX  ›  Go 编程语言

请问 gorm 如何获取到更新后的值

  •  
  •   swxc · 2020-09-20 21:57:43 +08:00 · 1448 次点击
    这是一个创建于 1304 天前的主题,其中的信息可能已经有所发展或是发生改变。
    type Counter struct {
    	BizName   string `gorm:"primary_key"`
    	NextId    string
    	CreatedAt time.Time
    }
    
    
    counter := model.Counter{BizName: "class"}
    
    err = d.Model(&counter).Update(ctx, "next_id", gorm.Expr("next_id  + ?",1)).Error
    
    

    想实现一个简易的发号器,想利用 mysql update 的原子性,更新 NextId 并获取到更新后的值,请问如何搞定

    4 条回复    2020-09-21 18:16:47 +08:00
    wleven
        1
    wleven  
       2020-09-21 09:12:35 +08:00
    d.Model(&counter).Update(ctx, "next_id", gorm.Expr("next_id + ?",1)).Find(&counter).Error
    crclz
        2
    crclz  
       2020-09-21 09:35:15 +08:00
    利用 postgresql 的 Returning 关键字。mysql 或者其他估计也有对应的解决方案。
    ghjacky
        3
    ghjacky  
       2020-09-21 12:53:23 +08:00
    d.Model(&counter).Debug().Update(ctx, "next_id", gorm.Expr("next_id + ?",1))
    xuegj1010
        4
    xuegj1010  
       2020-09-21 18:16:47 +08:00
    d.Model(&counter).Update(ctx, "next_id", gorm.Expr("next_id + ?",1)).Find(&counter).Scan(&counter).Error
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3059 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 14:52 · PVG 22:52 · LAX 07:52 · JFK 10:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.