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

gorm 不更新 0 值的问题,大家有好的方式吗

  •  
  •   uniy · 50 天前 · 1390 次点击
    这是一个创建于 50 天前的主题,其中的信息可能已经有所发展或是发生改变。

    已知的方式:
    1 、字段使用指针
    2 、Updates 参数使用 map
    3 、使用 select 函数,然后 Updates
    感觉都不太智能.

    9 条回复    2024-03-11 09:17:30 +08:00
    Rehtt
        1
    Rehtt  
       50 天前 via Android
    写一个专门更新的 struct ,字段用指针
    lxz6597863
        3
    lxz6597863  
       50 天前
    UpdateColumns 好像是可以更新 0 值的,但它好像不触发 hook,没用 hook 的话就用它
    dobelee
        4
    dobelee  
       50 天前
    写个反射函数,把 struct 转成 map 。
    EchoGroot
        5
    EchoGroot  
       50 天前
    可以参考下我处理接口参数零值的方式,还算优雅,从请求到入库
    https://github.com/EchoGroot/kratos-examples
    ZXiangQAQ
        6
    ZXiangQAQ  
       50 天前
    Save 方法不行么,存所有的字段,即使字段是零值
    I2E
        7
    I2E  
       49 天前
    map
    uniy
        8
    uniy  
    OP
       49 天前
    @bv @ZXiangQAQ save 也是一种解决方案,但是如果 model 里有 id ,created_at 这类字段的话,也会被更新到数据库,还需要特殊处理,比如用 omit 函数
    uniy
        9
    uniy  
    OP
       47 天前
    @EchoGroot 学到了,转换过程中去除了 autoCreateTime 、autoUpdateTime 字段
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   883 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:29 · PVG 05:29 · LAX 14:29 · JFK 17:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.