我试图找出如何通过一个表单将数据通过一个表单插入不同的表(多对多关系)来进行mySQL查询。我的表格如下 -
https://i.stack.imgur.com/1xTkd.jpg
我真的很难找到一个mySQL语句加入Pokemon&用于在特定位置创建新口袋妖怪的位置表。有任何想法吗?
router.post('/', function(req, res){
var mysql = req.app.get('mysql');
var sql = "INSERT INTO pokemon (pokemonname, evolutionlevel) VALUES(?,?)";
var sql2 = "INSERT INTO location (locationname) VALUES(?, ?)";
var inserts = [req.body.pokemonname, req.body.evolutionlevel, req.body.locationname];
sql = mysql.pool.query(sql, sql2, inserts, function(error, results, fields){
if(error){
res.write(JSON.stringify(error));
res.end();
} else{
res.redirect('/location');
}
});
});
答案 0 :(得分:0)
我不明白你为什么要加入表格来插入。你可以用两个不同的语句来完成,如下所示
router.post('/', function(req, res){
var mysql = req.app.get('mysql');
var sql = "INSERT INTO pokemon (pokemonname, evolutionlevel) VALUES(?,?)";
var sql2 = "INSERT INTO location (locationname) VALUES(?, ?)";
var insert1 = [req.body.pokemonname, req.body.evolutionlevel];
var insert2 = [req.body.locationname];
var first_sql = mysql.pool.query(sql, insert1, function(error, results, fields){
if(error){
res.write(JSON.stringify(error));
res.end();
} else {
var second_sql = mysql.pool.query(sql2, insert2, function(error, results, fields){
if(error){
res.write(JSON.stringify(error));
res.end();
}
});
res.redirect('/location');
}
});
});