Field multiplication in Sequelize

Asked

Viewed 55 times

0

I have the following code thingy:

const buys = await Buy.findAll({
  where: {
    account_id: req.params.id,
  },
  attributes: ['id', 'account_id', 'buy_value', 'quantity'],
});

return res.json(buys);

That returns me the following JSON:

{
    "id": 9,
    "account_id": 3,
    "buy_value": "49521.00",
    "quantity": 2
}

I would like to return within the same JSON, a field teste that multiplies the fields buy_value and quantity. How can I do ?

1 answer

1


I solved it as follows. I used the literal of Sequelize:

import { literal } from 'sequelize';

const buys = await Buy.findAll({
      where: {
        account_id: req.params.id,
      },
      attributes: [
        'id',
        'account_id',
        'buy_value',
        'quantity',
        [literal('buy_value * quantity'), 'test_field'],
      ],
    });

    return res.json(buys);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.