[英]Update multiple rows in sequelize with different conditions
我正在尝试对 postgres 数据库中的行执行带有 sequelize 的更新命令。 我需要能够更新具有相同值的不同条件的多行。
例如,假设我有一个包含以下字段的用户表:
假设,我在这个表中有 4 条记录,我想用一个新的位置更新 ID - 1 和 4 的记录,比如尼日利亚。
像这样: SET field1 = 'foo' WHERE id = 1, SET field1 = 'bar' WHERE id = 2
我怎样才能通过 sequelize 实现这一目标?
您可以一次更新多个记录,但对所有记录进行相同的更新,如果您想对不同的条件进行不同的更新,则必须多次运行。
示例:
这会将fields1
更新为 foo ,其中id
为 1 或 4
let ids = [1,4];
Your_model.update({ field1 : 'foo' },{ where : { id : ids }});
这将更新field1
为foo如果id
是1, field1
吧,如果id
为4
Your_model.update({ field1 : 'foo' },{ where : { id : 1 }});
Your_model.update({ field1 : 'bar' },{ where : { id : 4 }});
希望这能解决你所有的疑惑。
您可以根据您的条件更新多行,为此操作员非常有帮助。
看这里: 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
}
}
)
有各种各样的操作符,包括范围操作符,或者像操作符...等
更新时的重要问题之一是如何更新所有行?
不包括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
});
我们计划为多行中的相同字段保存不同的值,有可能使数据库中的所有字段值都相同。 使用 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});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.