我现在有2个问题。首先,我想知道如何在一个请求中在ma表中插入其他数据,
app.post('/api/domain/:id/translation.json', function (req, res) {
var domain_id = req.params.id;
ADD this// Insert INTO translation_to_lang ('lang_id' which mean result.insertID, 'value') VALUES ("' + req.body.lang_id + '", "' + req.body.value + '");
connection.query("INSERT INTO translation (`key`, `domain_id`) VALUES ('" + req.body.key + "', '" + domain_id +"');", function(error, result) {
if (error) throw(error);
var domain_id = result[0];
if (domain_id !== undefined) {
setTimeout(function () {
res.status(400);
res.send({
code: 400,
message: 'Bad Request'
});
}, 1000);
}
console.log(result);
connection.query('SELECT * FROM translation WHERE id = "' + result.insertId + '"', function(error, data_insert) {
setTimeout(function () {
res.send({
code: 201,
message: 'success',
datas: data_insert
});
}, 1000);
});
});
});
我尝试发布不存在的domain_id数据时出错,如果尝试make条件,例如 ' / api / domain / 44 / translation .json' ,我的bdd在域名行中没有44个id我想要比我的api res发送状态400坏请求但我的条件不起作用我有此错误消息:
ER_NO_REFERENCED_ROW_2:无法添加或更新子行:外键约束失败(
restapi
。translation
,CONSTRAINTtranslation_ibfk_1
FOREIGN KEY(domain_id
)参考domain
(id
))
它只是从帖子而不是有问题,但如果你想看到所有人都说我。
答案 0 :(得分:0)
insert语句失败,因为该外键必须存在于相关表上,这会引发错误。
因此,您对结果[0]的检查无关紧要。您需要检查错误本身。如评论中所述,您也可以考虑 SQL注入的 mysql.format ,例如
var query = mysql.format("SELECT * FROM translation WHERE id = ?;", tId);
尝试使用
等代码app.post('/api/domain/:id/translation.json', function(req, res) {
var insertQuery = mysql.format("INSERT INTO translation (`key`, `domain_id`) VALUES (?,?);", [req.body.key, domain_id]);
connection.query(insertQuery, function(error, result) {
if (error) {
// check for constraint error
return res.status(400).send({
code: 400,
message: 'Bad Request'
});
}
console.log(result);
var selectQuery = mysql.format("SELECT * FROM translation WHERE id = ?;", result[0].insertId);
connection.query(selectQuery, function(error, data_insert) {
return res.send({
code: 201,
message: 'success',
datas: data_insert
});
});
});});