繁体   English   中英

为什么我的 sequelize 查询总结了一个十进制列作为字符串返回

[英]why is my sequelize query that sums a decimal column returning as a string

我正在对一个十进制列求和,它以字符串而不是整数的形式返回?

exports.sumMoney = function (id) {
    return myModel.findAll({
        raw: true,
        attributes: [[sequelize.fn('SUM', sequelize.col('moneycol')), 'moneylabel']],
        where: { id: id }
    }).then(r => r);
}

为了将结果转换为数字,您需要使用 sequelize.cast 函数执行显式转换:

exports.sumMoney = function (id) {
    return myModel.findAll({
        raw: true,
        attributes: [[sequelize.cast(sequelize.fn('SUM', sequelize.col('moneycol')), 'int'), 'moneylabel']],
        where: { id: id }
    }).then(r => r);
}

我不知道为什么它没有在 sequelize v4 文档中说明,但 v3 指出:

postgres 需要显式转换。

http://sequelize.readthedocs.io/en/v3/api/sequelize/#fnfn-args-sequelizefn

我不确定您使用的是 MySQL 还是 Postgres,但是将其添加到配置中解决了我在 MySQL 上的问题

dialectOptions: {
    decimalNumbers: true
}

几天前我确实解决了这个问题。 只有您需要使用SIGNED而不是int

[Transacciones.sequelize.cast(Transacciones.sequelize.fn('SUM', Transacciones.sequelize.col('fare')), 'SIGNED'), 'fare'],

我找到了两种解决方法

  1. 通过在模型中传递get()方法

    discountPercentage: { type: DataTypes.DECIMAL(18, 3), allowNull: true, defaultValue: 0.000, get() { return parseFloat(this.getDataValue('discountPercentage')) || null; } },
  2. 通过设置dialectOptions与 ow3n 的答案相同(我已尝试使用 MySQL)

     new Sequelize('mysql://root@localhost:3306/database',{ dialectOptions: { decimalNumbers: true } })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM