问题描述
我正在尝试进行以下交易:
static async save(habit){
await db.beginTransaction;
try {
await db.execute('SELECT @habitId:=MAX(habits.habitId)+1 FROM habits');
await db.execute('INSERT INTO habits(habits.habitId,habits.name,habits.repeatVal,habits.notification,habits.color,habits.question,habits.id) VALUES (@habitId,?,?)',[habit.name,habit.repeatVal,habit.notification,habit.color,habit.question,habit.id]);
await db.execute('INSERT INTO habit_status(habit_status.habitId,habit_status.date,habit_status.status) VALUES (@habitId,"2021-04-01",0),(@habitId,"2021-04-02","2021-04-03","2021-04-04","2021-04-05","2021-04-06","2021-04-07","2021-04-08",0)');
await db.commit();
} catch (err) {
console.error(`Error occurred while creating habit: ${err.message}`,err);
db.rollback(function(){});
console.info('Rollback successful');
return 'error creating habit';
}
}
不幸的是,我收到以下错误:
创建习惯时发生错误:无法添加或更新子行:外键约束失败 (intend
.habit_status
,CONSTRAINT habit
FOREIGN KEY (habitId
) REFERENCES habits
(habitId
) ON DELETE CASCADE) 错误:无法添加或更新子行:外键约束失败 (intend
.habit_status
,CONSTRAINT {{1} } 外键 (habit
) 参考 habitId
(habits
) 删除级联)
还有:
habitId
我认为这是因为@habitId 可能没有将habitId 传递给我的第三个执行函数。但为什么?以及如何解决这个问题?
解决方法
至少你没有正确调用 beginTransaction
忘记添加括号:
await db.beginTransaction();
从 db.rollback
开始,尝试检查 db
是否真的是您期望的数据库连接对象。
我们可以发出 await db.commit();在第一个 INSERT 语句之后。