簡體   English   中英

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

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

我有這篇文章,我在其中執行插入,我需要獲取 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',
                              });

                        });
                });

          });
});

它有效,但它給了我一個錯誤

C:\Users\lcardemi\Desktop\PROYECTO CARD 3.0\backend\node_modules\mysql\lib\protocol\Parser.js:437 throw err; // 重新拋出非 MySQL 錯誤 ^ 錯誤 [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

步驟1。

執行INSERT INTO pages (name_page) VALUES (?)提供[page]作為參數。

第2步。

執行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 =? 提供[card, page]作為參數。 僅當pages.name_page定義為唯一時才適用。

或者執行INSERT INTO cards (id_page, container_card) VALUES (LAST_INSERT_ID(), ?)提供[card]作為參數。 但是您必須在同一個連接中執行此查詢,並且您必須保證在第 1 步和第 2 步之間沒有執行任何查詢,包括連接器發送的隱藏語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM