Interface. Batch Update Data
12003In certain scenarios, you may need to batch update multiple records in the database. jianghuKnex supports batch update operations in both the front-end page and the API. Here are two methods to implement batch updates:
Batch Update in the Page: Use a for loop to call the SQL resource in the front-end page.
Batch Update in the API: Perform a for loop update in the back-end service, or calculate the difference list and then use Promise.all for the update.
Batch Update in the Page
- Call SQL resource in a
forloop within the page
const studentList = [{studentId: 'S10001', studentStatus: 'Normal'}, {studentId: 'S10003', studentStatus: 'Graduated' }];
for (const item of studentList) {
await window.jianghuAxios({
data: {
appData: {
pageId: 'frontendDemo',
actionId: 'updateItem',
actionData: { studentStatus: item.studentStatus },
where: { studentId: item.studentId }
}
}
})
}Batch Update in the API
- Call a service interface in the page, and use a for loop to update in the service interface
const studentList = [{studentId: 'S10001', studentStatus: 'Normal'}, {studentId: 'S10003', studentStatus: 'Graduated' }];
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 });
}
})- Note: If the batch update exceeds 20 records, it is recommended to calculate the diffList and then use
Promise.allfor the update
const newStudentList = [{studentId: 'S10004', studentStatus: 'Graduated'}, {studentId: 'S10005', studentStatus: 'Graduated' }];
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;
});
});
}