【问题标题】:GORM decimal operations in Raw SQL query in UPDATEUPDATE 中 Raw SQL 查询中的 GORM 十进制运算
【发布时间】:2021-08-28 04:39:18
【问题描述】:

我正在使用 GORM postgres SQL 编写我的数据库查询,并在 GORM 中有一个原始 SQL 查询,如下所示

convertedCurr = points.Div(config.BaseFactor).Round(2)

sqlCoins := "UPDATE coins SET coins = coins + ?, points = points + ? WHERE tenant = ? AND user_id = ?"
errUpdateCoins = database.GetDbWriteClient().Raw(sqlCoins, convertedCurr, points, tenant, userId).Scan(&coin).Count(&updatedCount).Error

coinsdecimal.Decimal 类型,config.BaseFactor 也是。问题是我不可能再对它进行+ plus 操作,就像对整数类型一样。这归结为 text + unknown is invalid operation 作为错误日志。

我可以在这里运行哪些选项来完成这项工作?

  1. 我应该把它转换成浮点数吗?
  2. 有什么方法可以修改查询以使其正常工作?我看到 postgres 确实支持 decimal 原生类型。 https://www.postgresql.org/docs/10/datatype-numeric.html 因此,它归结为在原始 SQL 查询字符串中编写语法以使用变量以及先前的数据库值来更新硬币。

谢谢!

【问题讨论】:

    标签: postgresql go go-gorm


    【解决方案1】:

    您应该能够摆脱 SQL 中的一些类型转换:

    sqlCoins := "UPDATE coins SET coins = coins + ?::numeric, points = points + ?::numeric WHERE tenant = ? AND user_id = ?"
    

    sqlCoins := "UPDATE coins SET coins = coins + cast(? as numeric), points = points + cast(? as numeric) WHERE tenant = ? AND user_id = ?"
    

    “未知”伪类型"Identifies a not-yet-resolved type, e.g., of an undecorated string literal"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      • 2012-03-08
      • 2017-11-07
      • 2012-09-12
      • 1970-01-01
      • 2022-08-23
      相关资源
      最近更新 更多