1

I need to increment a column with 1 on some occasions, but the default value of that column is null and not zero. How do I handle this case using sequelize? What method could be utilized?

I could do by checking the column for null in one query and updating it accordingly in the second query using sequelize but I am looking for something better. Could I handle this one call?

2 Answers 2

2

I'll confess that I'm not terribly experienced with sequelize, but in general you'll want to utilize IFNULL. Here's what the raw query might look like:

UPDATE SomeTable SET some_column = IFNULL(some_column, 0) + 1 WHERE <some predicate> 

Going back to sequelize, I imagine you're trying to use .increment(), but judging from the related source, it doesn't look like it accepts anything that will do the trick for you.

Browsing the docs, it looks like you might be able to get away with something like this:

SomeModel.update({ some_column: sequelize.literal('IFNULL(some_column, 0) + 1') }, { where: {...} }); 

If that doesn't work, you're probably stuck with a raw query.

Sign up to request clarification or add additional context in comments.

Comments

0

First you need to find the model instance and update via itself, or update directly via Sequelize Static Model API.

Then you'll check whether the updated field got nullable value or not ? If fails then do the manual update as JMar propose above

await model.transaction({isolationLevel: ISOLATION_LEVELS.SERIALIZABLE}, async (tx) => { const user = await model.User.findOne({ where: { username: 'username', }, rejectOnEmpty: true, transaction: tx, }); const updatedRecord = await user.increment(['field_tag'], { transaction: tx, }); if (!updatedRecord.field_tag) { /** Manual update & Convert nullable value into Integer !*/ await model.User.update({ field_tag: Sequelize.literal('IFNULL(field_tag, 0) + 1') }, { where: { username: 'username', }, transaction: tx, }); } }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.