[英]multiple inserts node.js
我是 node.js 的新手,我在 sql 数据库中有 2 个表,一个名为 club 的表和一个名为 player 的表,它们通过一对多关系连接,所以我在 ZC047B10EEE763AFB6164E077CF1CC28 中创建了一个后查询,并从我的查询发送俱乐部名称、俱乐部价格以将其插入第一桌球队,并在同一查询中发送球队的选定球员列表并执行循环以将他们插入第二桌球员并插入每个球员的俱乐部 id,但我发现我自己不知道我应该在 Flutter 或 Node.js 中正确的是什么,我正在尝试为我尝试过的内容找到正确的语法,执行后我在 Z28A3689BE951688DD88ZE7A 中出现错误说 77A03
unexpected end of json input because probably of players(that is a table and not a field in table club)
这是我尝试过的:
create:(data,callback)=>{
pool.query(
insert into club(userid,name,price) values(?,?,?),
[
data.userid,
data.name,
data.price,
],
(error,results,fields)=>{
if(error){
callback(error);
}
return callback(null,results);
}
);
for(item in data.players){
pool.query(
`insert into players(id,firstname,lastname,position,price,appearences,goals,
assists,cleansheets,redcards,yellowcards,image,clubid) values(?,?,?,?,?,?,?,?,?,?,?,?,?)`,
[
data.players.id,
data.players.firstname,
data.players.lastname,
data.players.position,
data.players.price,
data.players.appearences,
data.players.goals,
data.players.assists,
data.players.cleansheets,
data.players.redcards,
data.players.yellowcards,
data.players.image,
data.players.clubid,
],
(error,results,fields)=>{
if(error){
callback(error);
}
return callback(null,results);
}
);
}
},
这是我的数据库的样子:
餐桌俱乐部: id userid
表球员: id firstname lastname position 价格出现 进球 助攻 不失球 红牌 黄牌 图片 clubid
clubid 是 table club 的外键我知道它应该是最后插入的 id 但我不知道如何做正确的语法
任何帮助将不胜感激
这里有两个问题。
首先,我猜,您将用于第二次 INSERT 的唯一clubid
是由 MySQL 的自动增量功能在您执行第一次 INSERT 时生成的。 您可以在result.insertId
查询的回调中获取它。 然后将其传递给第二个查询。
其次,您没有在此处正确处理 MySQL 查询的异步特性。 在您知道第一个 INSERT 完成之前,您不能执行第二个 INSERT。 因此,您必须从第一个查询的回调中执行第二个 INSERT。
或者更好的是使用mysql2 package和async
/ await
。 像这样的东西(未调试)。
create: async (data,callback) => { /* async! */
const myPool = pool.promise() /* promise! */
const {results, fields} = await myPool.query( /* await! */
'insert into club(userid,name,price) values(?,?,?)',
[ data.userid, data.name, data.price] )
const clubid = results.insertId
for(item in data.players) {
const {results, fields} = await myPool.query( /* await! */
`insert into players
(id, firstname, lastname, position,
price, appearences, goals, assists,
cleansheets, redcards, yellowcards,
image, clubid)
values(?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[ /* NOTE use item.whatever not data.players.whatever,
* because data.players is an array of objects */
item.id, item.firstname, item.lastname, item.position,
item.price, item.appearences, item.goals, item.assists,
item.cleansheets, item.redcards, item.yellowcards,
item.image,
clubid ] /* NOTE not item.clubid ! */
)
} /* end for (item in data.players) */
}
}
专业提示:花每一秒的时间来弄清楚async
/ await
和相关的Promises
API 都是值得的。 如果你不这样做,你就会陷入所谓的“回调地狱”。 上面有一个牌子,上面写着“进入这里的人,放弃一切希望。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.