[Nodejs] MySQL Insert쿼리문을 통해 id 가져오기

one·2021년 10월 14일
0

[TIL]What I Want To Know...

목록 보기
12/22
post-thumbnail
const db = require('../db');

module.exports = {
  orders: {
    post: (userId, orders, totalPrice, callback) => {
      let orderSql = `
      insert into orders (user_id, total_price) values (${userId}, ${totalPrice})`;
      let itemSql = `insert into order_items (order_id, item_id, order_quantity) values ?`;

      db.query(orderSql, (error, result) => {
        if (result) {
          let params = orders.map(order => [result.insertId, order.itemId, order.quantity]);

          db.query(itemSql, [params], (error, result) => {
            callback(error, result);
          });
        }
      });
};

insert into 실행 후, 삽입된 데이터의 id를 가져올 때
result 객체의 insertId의 값을 가져오면 됨

The Result Object

  • When executing a query, a result object is returned.
    The result object contains information about how the query affected the table.
    The result object returned from the example above looks like this:
{
  fieldCount: 0,
  affectedRows: 14,
  insertId: 0,     
  serverStatus: 2,
  warningCount: 0,
  message: '\'Records:14  Duplicated: 0  Warnings: 0',
  protocol41: true,
  changedRows: 0
}
profile
늘 호기심을 갖고, 새로운 것에 도전할 것.

0개의 댓글