首页 > 解决方案 > 为什么我的 sequelize 查询将十进制列作为字符串返回

问题描述

我正在对十进制列求和,它作为字符串而不是整数返回?

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

标签: javascriptnode.jssequelize.js

解决方案


为了将结果转换为数字,您需要使用 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


推荐阅读