V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
uniy

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

  •  
  •   uniy · Mar 8, 2024 · 2857 views
    This topic created in 780 days ago, the information mentioned may be changed or developed.

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

    9 replies    2024-03-11 09:17:30 +08:00
    Rehtt
        1
    Rehtt  
       Mar 8, 2024 via Android
    写一个专门更新的 struct ,字段用指针
    lxz6597863
        3
    lxz6597863  
       Mar 8, 2024
    UpdateColumns 好像是可以更新 0 值的,但它好像不触发 hook,没用 hook 的话就用它
    dobelee
        4
    dobelee  
       Mar 8, 2024
    写个反射函数,把 struct 转成 map 。
    EchoGroot
        5
    EchoGroot  
       Mar 8, 2024
    可以参考下我处理接口参数零值的方式,还算优雅,从请求到入库
    https://github.com/EchoGroot/kratos-examples
    ZXiangQAQ
        6
    ZXiangQAQ  
       Mar 8, 2024
    Save 方法不行么,存所有的字段,即使字段是零值
    I2E
        7
    I2E  
       Mar 9, 2024
    map
    uniy
        8
    uniy  
    OP
       Mar 9, 2024
    @bv @ZXiangQAQ save 也是一种解决方案,但是如果 model 里有 id ,created_at 这类字段的话,也会被更新到数据库,还需要特殊处理,比如用 omit 函数
    uniy
        9
    uniy  
    OP
       Mar 11, 2024
    @EchoGroot 学到了,转换过程中去除了 autoCreateTime 、autoUpdateTime 字段
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5451 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 157ms · UTC 05:55 · PVG 13:55 · LAX 22:55 · JFK 01:55
    ♥ Do have faith in what you're doing.