最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - why is my sequelize query that sums a decimal column returning as a string - Stack Overflow

programmeradmin3浏览0评论

I am summing a decimal column and it is being returned as a string instead of an integer?

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

I am summing a decimal column and it is being returned as a string instead of an integer?

exports.sumMoney = function (id) {
    return myModel.findAll({
        raw: true,
        attributes: [[sequelize.fn('SUM', sequelize.col('moneycol')), 'moneylabel']],
        where: { id: id }
    }).then(r => r);
}
Share Improve this question asked Jul 4, 2018 at 2:39 RodRod 15.5k34 gold badges133 silver badges262 bronze badges 1
  • Please post the output of sumMoney. – Vivek Doshi Commented Jul 4, 2018 at 3:22
Add a comment  | 

4 Answers 4

Reset to default 11

I'm not sure if you're using MySQL or Postgres, but adding this to the configuration fixed my issue on MySQL

dialectOptions: {
    decimalNumbers: true
}

In order to convert result to number you need to perform explicit cast using sequelize.cast function:

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);
}

I don't know why it isn't stated in sequelize v4 docs, but v3 states that:

An explicit cast is required on postgres.

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

Some days ago i did fix that problem. Only you need to use SIGNED instead of int.

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

I found two ways to solve it

  1. By Passing get() method in Model

    discountPercentage: {
     type: DataTypes.DECIMAL(18, 3),
     allowNull: true,
     defaultValue: 0.000,
     get() {
       return parseFloat(this.getDataValue('discountPercentage')) || null;
     }
    },
    
  2. Same as ow3n's answer by setting dialectOptions (I have tried with MySQL)

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

评论列表(0)

  1. 暂无评论