2

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

2 Answers2

5

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

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
0

Sequelize increment & decrement

myIncrementFunc(id, incrementor) {
  User.findById(id).then(user => {
    return user.increment('tableColumnName', {by: incrementor})
  }).then(user => {})
}

Code taken form sequelize Instances tutorial for Incrementing & Decrementing: http://docs.sequelizejs.com/manual/tutorial/instances.html

Amos
  • 91
  • 3