Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract 2 fields in Sequelize

My query looks like this so far...

{
    where: {
      id: event.pathParameters.picId
    },
    'include': [{
      'model': db.reputations,
      'where': {
        'type': 'V_UP'
      },
      'as': 'up_reputations',
      'required': false
    }, {
      'model': db.reputations,
      'where': {
        'type': 'V_DONW'
      },
      'as': 'down_reputations',
      'required': false
    }],
    'attributes': [
      'id',
      'title',
      'data',
      'createdAt',
      [db.Sequelize.fn('count', db.Sequelize.col('up_reputations.type')), 'upVotes'],
      [db.Sequelize.fn('count', db.Sequelize.col('down_reputations.type')), 'downVotes']
    ]
}

What I need is one last attribute, score, to be upVotes - downVotes but I have no idea how to do this.

like image 624
Justin808 Avatar asked Nov 28 '25 06:11

Justin808


1 Answers

This should work:

'attributes': [
      'id',
      'title',
      'data',
      'createdAt',
      [db.Sequelize.fn('count', db.Sequelize.col('up_reputations.type')), 'upVotes'],
      [db.Sequelize.fn('count', db.Sequelize.col('down_reputations.type')), 'downVotes'],
      [db.Sequelize.literal('(upVotes - downVotes)'), 'score']
 ]
like image 62
Maria Ines Parnisari Avatar answered Nov 30 '25 19:11

Maria Ines Parnisari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!