我有一个API调用,它在多个表中创建记录,同时在所有表中使用并插入相同的id作为外键。我已经制作了下面的代码,在我的脑海中,它将循环通过每个表的正确查询来创建我需要的内容。
const auditTables = ['audit_general', 'audit_culture',
'audit_performance', 'audit_policies', 'audit_risk', 'audit_strategy',
'audit_rewards', 'audit_workforce'];
app.put("/interview/create/questions/:lastEmployeeId", function (req, res) {
console.log("It is getting to the route");
const employee_id = req.body.lastEmployeeId;
connection.getConnection(function (err, connection) {
for (i = 0; i < auditTables.length; i++) {
connection.query(
`INSERT INTO ${auditTables[i]} (employee_id) VALUES (?)`,
[employee_id],
function (error, results, fields) {
if (error) throw error;
res.json(results);
console.log(`Interview for ${auditTable[i]} has been created.`);
}
)
};
connection.release();
})
});
然而,当我尝试运行它时,它会使服务器崩溃。但当我使用这个路由,只添加到其中一个表时,它非常有效。唯一不同的是循环。我可以不做循环,而需要实际写出所有8个查询吗?
这个有效:
app.put("/interview/create/questions/:lastEmployeeId", function (req, res) {
console.log("It is getting to the route");
const employee_id = req.body.lastEmployeeId;
connection.getConnection(function (err, connection) {
connection.query(
`INSERT INTO audit_general (employee_id)
VALUES (?)`,
[employee_id],
function (error, results, fields) {
if (error) throw error;
res.json(results);
console.log(`Interview has been created`);
}
);
connection.release();
});
});
for (i = 0; i < auditTables.length; i++)
那里面不应该有VAR吗?
for (var i = 0; i < auditTables.length; i++)