【发布时间】:2021-06-30 16:20:27
【问题描述】:
在前端,每当我按下提交问题的答案时,它都会创建 1 个包含这些列的 result_ID。
result_ID 是自动递增的,question_ID 是与 questions 表中相同 question_ID 的关系。
如果这是用户第一次选择答案,它将创建一个 answer_result(我在 answer_ID 中解析)和 answer_checkResult(值 1 或 0 来识别它的正确或不正确),以及一个 history_ID 来分别识别每条记录。
History_ID 是具有 quiz_ID(用于识别主题)和 user_ID 的不同表
示例:History_ID 221 有 4 个问题,有 4 个答案和 4 个 answer_result。
我不知道的是,如果该行不存在,我如何创建一个情况,它将运行 INSERT INTO 情况,否则如果它已经存在(因为用户可以在 1 中多次更改答案问题),它会更新。我刚刚只创建了 INSERT INTO 选项,但我不知道如何在此模型中同时使用 INSERT INTO 进行更新。
这是我创建的history_result.model,我不知道如何创建一个if-else来同时更新和创建......
history_result.model
const HistoryResult = function (history_result) {
this.question_ID = history_result.question_ID;
this.answer_result = history_result.answer_result;
this.answer_checkResult = history_result.answer_checkResult;
this.history_ID = history_result.history_ID;
};
HistoryResult.create = async (newHistoryResult, result) => {
await db.query(
`INSERT INTO history_result SET question_ID = ?, answer_result = ?, answer_checkResult = ?, history_ID = ?`,
[
newHistoryResult.question_ID,
newHistoryResult.answer_result,
newHistoryResult.answer_checkResult,
newHistoryResult.history_ID,
],
(err, data) => {
if (err) {
result(err, null);
return;
} else {
return result(null, data);
}
}
);
};
这就是我创建 history_result 控制器的方法
const HistoryResult = require("../models/history_result.model");
exports.createHistoryResult = async (req, res) => {
let { history_ID } = req.params;
let { question_ID, answer_result, answer_checkResult } = req.body;
let historyResult = new HistoryResult({
question_ID: question_ID,
answer_result: answer_result,
answer_checkResult: answer_checkResult,
history_ID: history_ID,
});
HistoryResult.create(historyResult, (err, data) => {
if (err) {
res.status(500).send({
message: err.message || "Error while creating result",
});
}
res.send(data);
});
};
无论如何我可以做到这一点吗?谢谢。
【问题讨论】:
-
我之前搜索过ON DUPLICATE KEY UPDATE,但我不知道如何在我的情况下正确使用它,所以我不知道我做错了还是这样不适用于我的情况...
-
Images 不应用于文本数据,例如数据库内容。
-
由于 SQL 包含数据定义,minimal reproducible example 用于SQL question 应包括DDL 示例表语句(而不是临时表规范)和DML 示例数据语句(而不是转储或临时格式)。所需的结果不需要以示例代码的形式呈现,因为结果是代码的输出,而不是代码本身。
标签: mysql sql node.js express model-view-controller