简体   繁体   English

如何在 node.js 和 mysql 的另一个插入中插入插入

[英]how to have an insert inside another insert in node.js and mysql

I have this post where I perform an insert and I need to get the id to be able to use it in another insert.我有这篇文章,我在其中执行插入,我需要获取 id 才能在另一个插入中使用它。

router.post('/save_card', verifyToken, (req, res) => {
      const page = req.body.page;
      const container_card = req.body.container_card;


      mysqlConnection.query('INSERT INTO pages (name_page) VALUES (?)', [page],
           (err, results, fields) => {
                if (err) throw err;
        
                container_card.forEach(card => {
                    mysqlConnection.query('INSERT INTO cards (id_page, container_card) VALUES (?,?)', [results.insertId, card],
                        (err, rows, fields) => {
                              if (err) throw err;
                              res.json({
                                        message: 'Card created successfully',
                              });

                        });
                });

          });
});

it works but it gives me an error它有效,但它给了我一个错误

C:\Users\lcardemi\Desktop\PROYECTO CARD 3.0\backend\node_modules\mysql\lib\protocol\Parser.js:437 throw err; C:\Users\lcardemi\Desktop\PROYECTO CARD 3.0\backend\node_modules\mysql\lib\protocol\Parser.js:437 throw err; // Rethrow non-MySQL errors ^ Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client // 重新抛出非 MySQL 错误 ^ 错误 [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Step 1.步骤1。

Execute INSERT INTO pages (name_page) VALUES (?) providing [page] as a parameter.执行INSERT INTO pages (name_page) VALUES (?)提供[page]作为参数。

Step 2.第2步。

Execute INSERT INTO cards (id_page, container_card) SELECT id, ? FROM pages WHERE name_page =?执行INSERT INTO cards (id_page, container_card) SELECT id, ? FROM pages WHERE name_page =? INSERT INTO cards (id_page, container_card) SELECT id, ? FROM pages WHERE name_page =? providing [card, page] as parameters.提供[card, page]作为参数。 Applicable only when pages.name_page is defined as unique.仅当pages.name_page定义为唯一时才适用。

Alternatively execute INSERT INTO cards (id_page, container_card) VALUES (LAST_INSERT_ID(), ?) providing [card] as parameter.或者执行INSERT INTO cards (id_page, container_card) VALUES (LAST_INSERT_ID(), ?)提供[card]作为参数。 But you must execute this query in the same connection, and you must guarantee that none query was executed between steps 1 and 2, including hidden statements sent by the connector.但是您必须在同一个连接中执行此查询,并且您必须保证在第 1 步和第 2 步之间没有执行任何查询,包括连接器发送的隐藏语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM