首页 > 解决方案 > mysql-js如何插入带有插入id的批量记录

问题描述

我的用例。

  1. 首先,我在表中插入一条记录grn_master
  2. 然后我得到它来向表insertedId中插入多条记录grn_detail

这是我的代码。

async function create(req, res, next) {
    const grn = req.body.grn;
    const supplier = req.body.supplier_id; //An object contains objects
    const location = req.body.location;
    try {
        let query = "INSERT INTO grn_master SET customer_supplier_id = ?,location_id =?";
        connection.query(query, [supplier, location], (error, results) => {
            if (error) {
                console.log(error);
                res.sendStatus(500);
            } else {
                const grn_number = results.insertedId;
                let query = "INSERT INTO grn_detail SET item_id=?,unit_price=?,qty=?,total=?,grn_master_id=??";

                connection.query(query, [grn, grn_number], (error, results) => {
                    if (error) {
                        res.sendStatus(500);
                        console.log(error);
                    } else {
                        res.sendStatus(200);

                    }
                })


            }
        })
    } catch (error) {
        console.log(error);
        res.sendStatus(500);
    }
}

如何使用Mysql-js实现这一点

标签: mysqlnode.jsmysqljs

解决方案


推荐阅读