如何使用Sequelize批量更新数据库中BusinessHours表的多行数据
用Sequelize批量更新门店营业时间表
假设你的BusinessHours模型已定义,包含字段day(1-7对应周一至周日)、open_time、close_time,且通过store_id关联单一门店。以下两种方式可实现一次查询完成所有天数的营业数据更新:
方式一:使用UPDATE结合CASE WHEN(推荐)
通过Sequelize的literal方法插入原生SQL的CASE WHEN逻辑,在单条UPDATE语句中完成所有行的更新:
const { BusinessHours, Sequelize } = require('./models'); // 准备待更新的营业时间数据 const updatedHours = [ { day: 1, open_time: '09:00', close_time: '21:00' }, { day: 2, open_time: '09:00', close_time: '21:00' }, { day: 3, open_time: '09:00', close_time: '21:00' }, { day: 4, open_time: '09:00', close_time: '21:00' }, { day: 5, open_time: '09:00', close_time: '22:00' }, { day: 6, open_time: '10:00', close_time: '22:00' }, { day: 7, open_time: '10:00', close_time: '20:00' }, ]; // 构建安全的CASE语句(避免SQL注入) const openCaseClauses = updatedHours.map(item => `WHEN ${item.day} THEN :open_${item.day}`).join(' '); const closeCaseClauses = updatedHours.map(item => `WHEN ${item.day} THEN :close_${item.day}`).join(' '); // 绑定参数 const replacements = {}; updatedHours.forEach(item => { replacements[`open_${item.day}`] = item.open_time; replacements[`close_${item.day}`] = item.close_time; }); // 执行批量更新 await BusinessHours.update( { open_time: Sequelize.literal(`CASE day ${openCaseClauses} ELSE open_time END`), close_time: Sequelize.literal(`CASE day ${closeCaseClauses} ELSE close_time END`), }, { where: { store_id: 1 }, // 替换为你的门店ID replacements, } );
方式二:使用bulkCreate配合updateOnDuplicate
需提前在数据库中给store_id和day设置联合唯一约束,这样当数据已存在时会自动更新指定字段:
const { BusinessHours } = require('./models'); // 待更新数据同方式一 const updatedHours = [...]; await BusinessHours.bulkCreate(updatedHours, { updateOnDuplicate: ['open_time', 'close_time'], // 存在重复时更新的字段 where: { store_id: 1 }, // 限定目标门店 });
注意事项
- 方式一无需额外数据库约束,兼容性更强;方式二依赖联合唯一约束,实现更简洁。
- 所有涉及用户输入的时间值,务必使用参数绑定(如方式一的
replacements),避免SQL注入风险。
内容的提问来源于stack exchange,提问作者Flutter Dev
相关产品推荐
相关产品推荐

