Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'select if' function with sequelize in nodejs

I am developing a rest api in nodejs. I am using the sequelize library with a postgresql database.

With sequelize in nodejs I want to get a temporary column to manage some values. I have two column vip_start and vip_end. These columns are DataTypes.DATEONLY format.

When I select all the columns, I want to compare two dates, and finally create a new column with the answer. If true then 1, else 0. And then I want to order the selected rows by VIP_ANSWER (1 or 0).

In mysql it solves that like this:

( SELECT IF (CURDATE( ) >= DATE( vip_start ) AND CURDATE( ) <= DATE( vip_end ), 1, 0 ) ) as vip

How can I make it in sequelize? :

const datetime = new Date();
return Phones
    .findAll({
        attributes: ['id', 'description',  'vip_start', 'vip_end','user_id' ],//I want to there new column like vip_answer [1,0] and order by this values
         where: {
             enabled: 1,
             vip_start: { $lte: datetime }, // in there i am stopped (((
         },
       })
    .then(phone => res.status(200).send(phone));

Any help will be appreciated.

like image 264
Benfactor Avatar asked Feb 22 '26 07:02

Benfactor


1 Answers

Just add

[ sequelize.literal('( SELECT IF (CURDATE( ) >= DATE( vip_start ) AND CURDATE( ) <= DATE( vip_end ), 1, 0 ) )'),'vip']

To your attribute list :

attributes: ['id', 'description',  'vip_start', 'vip_end','user_id' , [ sequelize.literal('( SELECT IF (CURDATE( ) >= DATE( vip_start ) AND CURDATE( ) <= DATE( vip_end ), 1, 0 ) )'),'vip'] ]
like image 113
Vivek Doshi Avatar answered Feb 24 '26 20:02

Vivek Doshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!