Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition and Subtraction Assignment Operator With Sequelize

I would like to do an update by doing a simple addition on Sequelize.

table:

id || data
 1 ||  10 

sample:

db.table.update({ data : 1 }, { where: { id: 1 }});

after this query

id || data
 1 ||  11

I know it's a simple question, but I could not find the solution.

Which operator can I add and subtract? Thank you


1 Answers

Here it is :

db.table.update({ field: Sequelize.literal('data + 1') }, { where: { id: 1 }}))

OR

User.findById(1).then(user => {
  // -----> First Way
  return user.increment('my-integer-field', {by: 2});
  // -----> Second Way
  return user.increment([ 'my-integer-field', 'my-very-other-field' ], {by: 2})
  // -----> Third Way
  return user.increment({
     'my-integer-field':    2,
     'my-very-other-field': 3
  })
});

You can also do decrement by just replacing increment with decrement.


For Version6 :

await User.increment({age: 5}, { where: { id: 1 } }) // Will increase age to 15
await User.increment({age: -5}, { where: { id: 1 } }) // Will decrease age to 5

For more detail : DO READ

like image 157
Vivek Doshi Avatar answered Apr 20 '26 16:04

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!