Answer a question

I'm trying to perform an update command with sequelize on rows in a postgres database. I need to be able to update multiple rows that have different conditions with the same value.

For example, assume I have a user table that contains the following fields:

  • ID
  • First Name
  • Last Name
  • Gender
  • Location
  • createdAt

Assume, I have 4 records in this table, I want to update records with ID - 1 and 4 with a new location say Nigeria.

Something like this: SET field1 = 'foo' WHERE id = 1, SET field1 = 'bar' WHERE id = 2

How can I achieve that with sequelize?

Answers

You can update multiple record at a time , but same updates for all records , if you want to make different updates for different conditons then you have to run that multiple time

Example :

This will update fields1 to foo , where id is 1 or 4

let ids = [1,4];
Your_model.update({ field1 : 'foo' },{ where : { id : ids }}); 

This will update field1 to foo if id is 1 , and field1 to bar if id is 4

Your_model.update({ field1 : 'foo' },{ where : { id : 1 }});
Your_model.update({ field1 : 'bar' },{ where : { id : 4 }}); 

Hope this will clear all your doubts.

Logo

PostgreSQL社区为您提供最前沿的新闻资讯和知识内容

更多推荐