V
V
vladislav31012021-11-27 16:08:19
JavaScript
vladislav3101, 2021-11-27 16:08:19

How to return attribute value instead of object in Sequlize?

const transaction = await Transaction.findByPk(1, {
attributes: ['id'],
include: [
  {
    model: TransactionStatus,
    as: 'status',
    attributes: ['name']
  }
]
})

Result: Is it possible to assign a name value to the status key using the Sequelize parameters, or will I have to write a wrapper function that will return json to me in the desired format? Expected Result:
{id: 1, status: { name: "success" } }
{id: 1, status: "success" }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vladislav3101, 2021-11-27
@vladislav3101

Solution:
The col() method

const transaction = await Transaction.findByPk(1, {
attributes: [[sequelize.col('transactionStatus.name'), 'status'], 'id'],
include: [
  {
    model: TransactionStatus,
    as: 'transactionStatus',
    attributes: []
  }
]
})

I had to change the as key to another name. For some reason, Sequlize doesn't want to output a column named "status" when the "include" model has an as key with the same name (although the sql query runs and returns the data as expected).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question