【问题标题】:Update multiple rows in sequelize with different conditions用不同的条件更新 sequelize 中的多行
【发布时间】:2018-09-13 13:05:48
【问题描述】:

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

例如,假设我有一个包含以下字段的用户表:

  • 身份证
  • 名字
  • 姓氏
  • 性别
  • 位置
  • createdAt

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

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

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

【问题讨论】:

标签: javascript postgresql sequelize.js


【解决方案1】:

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

示例:

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

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

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

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

希望这能消除您的所有疑虑。

【讨论】:

  • 是的,确实如此。谢谢。
  • @proton,很高兴知道,谢谢,BTW 编码愉快。
  • @VivekDoshi 有什么方法可以通过单个更新查询来做到这一点。
【解决方案2】:

您可以根据您的条件更新多行,并且操作符非常有帮助。

看这里:http://docs.sequelizejs.com/manual/querying.html(操作员)

const { Op } = Sequelize;
DisplayMedia.update(
    {
        field: 'bar'
    },
    {
        where: {
            id: {
                [Op.in]: [1, 10, 15, ..]   // this will update all the records 
            }                           // with an id from the list
        }
    }
)

有各种各样的运算符,包括范围运算符,或like运算符...等

更新时的重要问题之一是如何更新所有行?

不包括where 会导致错误“传递给更新的选项参数中缺少 where 属性”。

答案在下面的代码中:为where 提供一个空对象

await DisplayMediaSequence.update({
    default: false
}, {
    where: {}, // <-- here
    transaction
});
await DisplayMediaSequence.update({ 
    default: true     <-- after all turned to false, we now set the new default. (that to show a practical expample) -->
}, {
    where: {
        id
    },
    transaction
});

【讨论】:

  • IMO 这应该是公认的答案,它直接解决了所提出的问题。谢谢
【解决方案3】:

我们计划为多行中的相同字段保存不同的值,这样可以使数据库中的所有字段值都相同。 使用 for 循环

const {idArray,group_id} = params;

for(const item of idArray){

    const response = await Your_model.findOne({ where:{group_id,user_id:null}, order: [['id', 'DESC']] });

    await response.update({user_id:item});
}

【讨论】:

    猜你喜欢
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    相关资源
    最近更新 更多