接口.批量更新数据

12003

在某些场景下,您可能需要批量更新数据库中的多条记录。jianghuKnex 支持在页面和接口中进行批量更新操作。以下是两种实现批量更新的方法:

页面内批量更新:在前端页面中使用 for 循环调用 SQL 资源。
接口内批量更新:在后端服务中进行 for 循环更新,或者计算差异列表后使用 Promise.all 进行更新。

页面里 批量更新

  • 在页面内for循环调用 sql resource
    1. const studentList = [{studentId: 'S10001', studentStatus: '正常'}, {studentId: 'S10003', studentStatus: '毕业' }];
    2. for (const item of studentList) {
    3. await window.jianghuAxios({
    4. data: {
    5. appData: {
    6. pageId: 'frontendDemo',
    7. actionId: 'updateItem',
    8. actionData: { studentStatus: item.studentStatus },
    9. where: { studentId: item.studentId }
    10. }
    11. }
    12. })
    13. }

接口里 批量更新

  • 页面里调用一个 service接口, service接口for循环更新
    1. const studentList = [{studentId: 'S10001', studentStatus: '正常'}, {studentId: 'S10003', studentStatus: '毕业' }];
    2. await this.app.jianghuKnex.transaction(async trx => {
    3. for (const item of studentList) {
    4. await trx("student", this.ctx)
    5. .where({ studentId: item.studentId })
    6. .jhUpdate({ studentStatus: item.studentStatus });
    7. }
    8. })
  • 注意:如果批量更新量超过20条,建议计算出diffList然后再用 Promise.all 更新
    1. const newStudentList = [{studentId: 'S10004', studentStatus: '毕业'}, {studentId: 'S10005', studentStatus: '毕业' }];
    2. const studentIdList = newStudentList.map(item => item.studentId);
    3. const oldStudentList = await this.app.jianghuKnex("student").whereIn('studentId', studentIdList).select();
    4. const diffStudentList = newStudentList.filter(newStudent => {
    5. const oldStudent = oldStudentList.find(item => item.studentId === newStudent.studentId);
    6. if (newStudent.studentStatus != oldStudent.studentStatus) { return true; }
    7. return false;
    8. });
    9. if (diffStudentList.length > 0) {
    10. await this.app.jianghuKnex.transaction(async trx => {
    11. const queries = diffStudentList.map(diffItem =>
    12. trx("student", this.ctx)
    13. .where({ studentId: diffItem.studentId })
    14. .update({ studentStatus: diffItem.studentStatus })
    15. );
    16. await Promise
    17. .all(queries).then(trx.commit)
    18. .catch((err) => {
    19. logger.error("[jianghuKnex.transaction error]", err);
    20. throw err;
    21. });
    22. });
    23. }