B
B
Bogdan2019-07-25 10:48:49
JavaScript
Bogdan, 2019-07-25 10:48:49

Sequelize to return calculated fields?

Tell me please. How to correctly make such a query in Sequelize (PostgreSQL)
1) several fields need to be contacted id || ' ' || id as somefield
2) one field rename code as codeCartidge,

select id || ' ' || id as somefield, code as codeCartidge, quantity, printed  from "Cartridges"

did it like this
const cartridges = await models.Cartridge.findAll({
    order: ['code'],
    attributes: [models.sequelize.literal("id || ' ' || id"), models.sequelize.literal('code AS codeCartridge'), 'quantity', 'printed']
  });

result:
[
        {
            "quantity": 500,
            "printed": 0
        },
        {
            "quantity": 500,
            "printed": 0
        },
   ...

It turns out as 2 fields, where the concentration and where the renaming fell out
, here is the result in the console:
Executing (default): SELECT id || ' ' || id, code AS codeCartridge, "quantity", "printed" FROM "Cartridges" AS "Cartridge" ORDER BY "Cartridge"."code"; { plain: false,
  raw: false,
  logging: [Function: bound consoleCall],
  order: [ 'code' ],
  attributes:
   [ Literal { val: 'id || \' \' || id' },
     Literal { val: 'code AS codeCartridge' },
     'quantity',
     'printed' ],
  hooks: true,
  rejectOnEmpty: false,
  originalAttributes:
   [ Literal { val: 'id || \' \' || id' },
     Literal { val: 'code AS codeCartridge' },
     'quantity',
     'printed' ],
  tableNames: [ 'Cartridges' ],
  type: 'SELECT',
  model: Cartridge }

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Bogdan, 2019-07-25
@bogdan_uman

It seems that I found a solution, for aliases you need to make a nested array

const cartridges = await models.Cartridge.findAll({
    order: ['code'],
    attributes: [[models.sequelize.literal("id || ' ' || id"), 'id'],
      ['code', 'codeCartridge'],
      'quantity', 'printed']
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question