Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select case query in sequelize?

I have a sql query:

SELECT field1, field2,
  CASE
    WHEN field1=1 THEN 'a'
    ELSE 'b'
  END 
  AS field3
FROM test

and I want to implement it with sequelizejs ,

const params = {
  attributes: //DO SELECT CASE,
};

yield Model.findAll(params);

Can anyone help me? Thank you.

like image 269
Mamen Avatar asked Nov 07 '16 10:11

Mamen


People also ask

How do you write a select query in Sequelize?

Sequelize instance comes with the query() method which you can use to run a raw query. The syntax of the method is as shown below: const [results, metadata] = await sequelize. query( "Your query here", { options } );

What does raw true do in Sequelize?

According to the doc : If you do not provide other arguments than the SQL, raw will be assumed to the true, and sequelize will not try to do any formatting to the results of the query.

How do I sort data in Sequelize?

To set the Sequelize findAll sort order in Node. js, we can set the order property. const getStaticCompanies = () => { return Company. findAll({ where: { //... }, order: [ ['id', 'DESC'], ['name', 'ASC'], ], attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'] }); };

How do you use OP in Sequelize?

You need to import the object from Sequelize to use it in your code: const { Sequelize, Op } = require("sequelize"); When you call the query methods from your model, you can use the Op object properties to create SQL queries with operators.


1 Answers

For the people that are still looking for this answer

Model.findAll({
  attributes: [[models.sequelize.literal('CASE WHEN "field1" = true THEN 55 ELSE 23 END'), 'field3']]
}

or

Model.findAll({
  attributes: { include: [[models.sequelize.literal('CASE WHEN "field1" = true THEN 55 ELSE 23 END'), 'field3']]}
}

So in my example when field1 is true it will return 55 else 23. This will generate a query like

SELECT CASE WHEN "field1" THEN 55 ELSE 23 END AS "field3" FROM "models"

For more information you can look in the documentation http://docs.sequelizejs.com/en/latest/docs/querying/#attributes

like image 111
Erwin Kraan Avatar answered Oct 25 '22 11:10

Erwin Kraan