[英]sequelize updating multiple rows
更新多行,使用批量更新是一个好的解决方案还是下面的代码有效? . 我想用 id 和文件名更新所有记录。
我确实尝试在循环内进行更新,但迁移挂起并且在此块中花费的时间太长。 是因为迭代吗? 还是更新语法有问题? 谢谢你。
#代码
for (let i = 0; i < documents.length; i++) {
const prefix = Date.now().toString();
const fileParts = documents[i].filename.split('.');
const finalname = `${fileParts[0]}-${prefix}.${fileParts[1]}`;
// eslint-disable-next-line no-await-in-loop
await queryInterface.sequelize.query(`UPDATE ${EmployeeDocumentsModel.tableName} SET filename='${finalname}' WHERE id=${documents[i].id};`, { transaction });
}
#代码
module.exports = {
up: async (queryInterface) => {
const transaction = await queryInterface.sequelize.transaction();
try {
const sequelizeClient = app.get('sequelizeClient');
const documents = await sequelizeClient.query(
`SELECT id, filename, COUNT(filename) FROM ${EmployeeDocumentsModel.tableName} GROUP BY filename
HAVING COUNT(filename) > 1;`,
{ type: QueryTypes.SELECT },
);
// eslint-disable-next-line no-plusplus
for (let i = 0; i < documents.length; i++) {
const prefix = Date.now().toString();
const fileParts = documents[i].filename.split('.');
const finalname = `${fileParts[0]}-${prefix}.${fileParts[1]}`;
// eslint-disable-next-line no-await-in-loop
await queryInterface.sequelize.query(`UPDATE ${EmployeeDocumentsModel.tableName} SET filename='${finalname}' WHERE id=${documents[i].id};`, { transaction });
}
// eslint-disable-next-line no-unused-vars
// const file = await sequelizeClient.query(
// `DELETE d1 from ${EmployeeDocumentsModel.tableName} d1 inner join ${EmployeeDocumentsModel.tableName} d2 on d2.id < d1.id and d2.filename = d1.filename and d2.employeeId = d1.employeeId`,
// { type: QueryTypes.DELETE },
// );
await queryInterface.addConstraint(EmployeeDocumentsModel.tableName, ['employeeId', 'filename'], {
type: 'unique',
name: 'composite_employee_filename',
}, {
transaction,
});
await transaction.commit();
} catch (err) {
// eslint-disable-next-line no-console
console.log(err);
await transaction.rollback();
throw err;
}
return true;
},
我认为最大的问题是每个更新都在等待上一个更新完成:
for (let i = 0; i < documents.length; i++) {
// ...
await queryInterface.sequelize.query(`UPDATE ${EmployeeDocumentsModel.tableName} SET filename='${finalname}' WHERE id=${documents[i].id};`, { transaction });
}
如果您将其更改为:
const promises = [];
for (let i = 0; i < documents.length; i++) {
// ...
promises.push(queryInterface.sequelize.query(`UPDATE ${EmployeeDocumentsModel.tableName} SET filename='${finalname}' WHERE id=${documents[i].id};`, { transaction }));
}
await Promise.all(promises);
你应该看到一个很大的加速。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.