我正在使用事务输出knexjs在2个表中插入值(1.结果,2。结果详细信息)。在表2中插入值(详细信息)时,我有一个对象数组,其大小随每个条目而变化(基于主题数)。
{
"name": "Sally",
"fathername": "John",
"rollno": "85a76",
"classname": "class1",
"detail": [
{
"subject": "History",
"marksobt": "50",
"totalmarks": "100"
},
{
"subject": "French",
"marksobt": "75",
"totalmarks": "75"
}
]
}
我正在尝试按照以下代码来执行此操作。 (同样,“详细”数组的大小随主题数的变化而变化)
const { name, fathername, rollno, classname } = req.body;
db.transaction(trx => {
db.insert({
name: name,
fathername: fathername,
rollno: rollno,
classname: classname
}).into('results')
.transacting(trx)
.returning('rollno')
.then(roll_no => {
req.body.detail.map(result => {
return trx('resultdetail')
.returning('*')
.insert({
rollno: roll_no[0],
subject: result.subject,
marksobt: result.marksobt,
totalmarks: result.totalmarks
}).then(console.log)
})
})
.then(trx.commit)
.catch(trx.rollback)
})
.catch(err => res.status(400).json(err))
Unhandled rejection Error: Transaction query already complete, run with DEBUG=knex:tx for more info
答案 0 :(得分:0)
insertedRows = await knex('results').returning('*').insert([
{
"subject": "History",
"marksobt": "50",
"totalmarks": "100"
},
{
"subject": "French",
"marksobt": "75",
"totalmarks": "75"
}
]);
但是主要的问题是,您启动多个查询+一次提交,而又没有等待早先的查询准备就绪...
在第二张表中添加内容时,应该是这样的:
.then(roll_no => {
let resultsToAdd = req.body.detail.map(result => {
return {
rollno: roll_no[0],
subject: result.subject,
marksobt: result.marksobt,
totalmarks: result.totalmarks
};
});
return return trx('resultdetail')
.returning('*')
.insert(resultsToAdd);
})