Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating with calculated values in Sequelize

I want to run an update query on my model using the previous value in one of the fields.

This updates the model (row id=4) the 'seq' field to 5.

 Model.update({
        seq: 5
    },{
        where:{
            'id':4,

        }
    });

Now how do I update the model to the previous value stored in the 'seq' field + 5 ?

 Model.update({
            seq: 'seq' + 5
        },{
            where:{
                'id':4,

            }
        });
like image 932
Yaron Avatar asked Apr 12 '19 07:04

Yaron


2 Answers

You can use

Model.update(
  { seq: sequelize.literal('seq + 5') },
  { where: { id: model_id } }
);

Or you can use the increment method

Model.increment('seq', { by: 5, where: { id: 'model_id' }});
like image 155
Łukasz Szewczak Avatar answered Sep 21 '22 01:09

Łukasz Szewczak


You can do this by using increment

 Model.increment(
        { seq: +5 },
        { where: { id: 4 } }
      );

and output:

UPDATE `Model` SET `seq`=`seq`+ 5 WHERE `id` = 4
like image 29
Sunny Sultan Avatar answered Sep 21 '22 01:09

Sunny Sultan