简体   繁体   中英

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.

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; // Rethrow non-MySQL errors ^ Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Step 1.

Execute INSERT INTO pages (name_page) VALUES (?) providing [page] as a parameter.

Step 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 =? providing [card, page] as parameters. Applicable only when pages.name_page is defined as unique.

Alternatively execute INSERT INTO cards (id_page, container_card) VALUES (LAST_INSERT_ID(), ?) providing [card] as parameter. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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