Multiplying fields in Sequelize select

I have the following code snippet:

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

    return res.json(buys);

Which returns the following JSON:

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

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

Upvotes: 0

Views: 295

Answers (1)

Anatoly
Anatoly

Reputation: 22803

Just use Sequelize.literal like this:

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

Upvotes: 1

Related Questions