我正在对十进制列求和,它以字符串而不是整数的形式返回?
exports.sumMoney = function (id) {
return myModel.findAll({
raw: true,
attributes: [[sequelize.fn('SUM', sequelize.col('moneycol')), 'moneylabel']],
where: { id: id }
}).then(r => r);
}
我不确定您使用的是MySQL还是Postgres,但是将其添加到配置中解决了我在MySQL上的问题
dialectOptions: {
decimalNumbers: true
}
为了将结果转换为数字,您需要使用 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);
}
我不知道为什么续集 v4 文档中没有说明,但 v3 指出:
帖子上需要显式强制转换。
http://sequelize.readthedocs.io/en/v3/api/sequelize/#fnfn-args-sequelizefn
几天前我确实解决了这个问题。 只有您需要使用SIGNED
而不是int
.
[Transacciones.sequelize.cast(Transacciones.sequelize.fn('SUM', Transacciones.sequelize.col('fare')), 'SIGNED'), 'fare'],
我找到了两种解决方法
-
通过在模型中传递get((方法
discountPercentage: { type: DataTypes.DECIMAL(18, 3), allowNull: true, defaultValue: 0.000, get() { return parseFloat(this.getDataValue('discountPercentage')) || null; } },
-
与ow3n通过设置方言选项的答案相同(我已经尝试过MySQL(
new Sequelize('mysql://root@localhost:3306/database',{ dialectOptions: { decimalNumbers: true } })