Update multiple rows in sequelize with different conditions(用不同的条件更新 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 中的多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用不同的条件更新 sequelize 中的多行
基础教程推荐
- npm start 错误与 create-react-app 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
