接口.批量更新数据
12003在某些场景下,您可能需要批量更新数据库中的多条记录。jianghuKnex 支持在页面和接口中进行批量更新操作。以下是两种实现批量更新的方法:
页面内批量更新:在前端页面中使用 for 循环调用 SQL 资源。
接口内批量更新:在后端服务中进行 for 循环更新,或者计算差异列表后使用 Promise.all 进行更新。
页面里 批量更新
- 在页面内
for循环调用 sql resourceconst studentList = [{studentId: 'S10001', studentStatus: '正常'}, {studentId: 'S10003', studentStatus: '毕业' }];for (const item of studentList) {await window.jianghuAxios({data: {appData: {pageId: 'frontendDemo',actionId: 'updateItem',actionData: { studentStatus: item.studentStatus },where: { studentId: item.studentId }}}})}
接口里 批量更新
- 页面里调用一个 service接口, service接口for循环更新
const studentList = [{studentId: 'S10001', studentStatus: '正常'}, {studentId: 'S10003', studentStatus: '毕业' }];await this.app.jianghuKnex.transaction(async trx => {for (const item of studentList) {await trx("student", this.ctx).where({ studentId: item.studentId }).jhUpdate({ studentStatus: item.studentStatus });}})
- 注意:如果批量更新量超过20条,建议计算出diffList然后再用
Promise.all更新const newStudentList = [{studentId: 'S10004', studentStatus: '毕业'}, {studentId: 'S10005', studentStatus: '毕业' }];const studentIdList = newStudentList.map(item => item.studentId);const oldStudentList = await this.app.jianghuKnex("student").whereIn('studentId', studentIdList).select();const diffStudentList = newStudentList.filter(newStudent => {const oldStudent = oldStudentList.find(item => item.studentId === newStudent.studentId);if (newStudent.studentStatus != oldStudent.studentStatus) { return true; }return false;});if (diffStudentList.length > 0) {await this.app.jianghuKnex.transaction(async trx => {const queries = diffStudentList.map(diffItem =>trx("student", this.ctx).where({ studentId: diffItem.studentId }).update({ studentStatus: diffItem.studentStatus }));await Promise.all(queries).then(trx.commit).catch((err) => {logger.error("[jianghuKnex.transaction error]", err);throw err;});});}