Update multiple rows in sequelize with different conditions(用不同的条件更新 sequelize 中的多行)

本文介绍了用不同的条件更新 sequelize 中的多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对 postgres 数据库中的行执行带有 sequelize 的更新命令.我需要能够用相同的值更新具有不同条件的多行.

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:

  • 身份证
  • 名字
  • 姓氏
  • 性别
  • 位置
  • 创建于

假设,我在此表中有 4 条记录,我想更新 ID 为 1 和 4 的记录,并使用新的位置,比如尼日利亚.

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

类似这样:SET field1 = 'foo' WHERE id = 1, SET field1 = 'bar' WHERE id = 2

如何通过 sequelize 实现这一目标?

How can I achieve that with sequelize?

推荐答案

您可以一次更新多条记录,但所有记录的更新相同,如果你想为不同的条件进行不同的更新,那么你必须多次运行

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

示例:

这会将 fields1 更新为 foo ,其中 id 是 1 或 4

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

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

如果 id 为 1 ,这会将 field1 更新为 foo ,如果 id 为 4 则将 field1 更新为 bar

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.

这篇关于用不同的条件更新 sequelize 中的多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!