首页 > 解决方案 > 在 foreach 循环中使用 knex 进行多链查询

问题描述

我是 node 和 knex 的新手,我在 mssql 上有名为“orders”、“orderdetails”和“customers”的表,看起来像

orders

orderdetails

使用 express.js 我想创建一个带有参数的页面OrderId并希望看到这个结果

  "OrderId": 1001,
  "CustomerId": 1,
  "OrderDate": "2021-09-30T20:00:55.000Z",
  "OrderPrice": 99.8,
  "OrderStatus": 4,
  "OrderStatusDescription": "Shipped",
  "OrderDetails": [
    {
      "OrderId": 1001,
      "ProductId": 1,
      "ProductName": "Model Car A",
      "Quantity": 1,
      "Price": 46.9,
      "NetAmount": 46.9
    },
    {
      "OrderId": 1002,
      "ProductId": 1,
      "ProductName": "Model Car B",
      "Quantity": 1,
      "Price": 52.9,
      "NetAmount": 52.9
    }
  ]
}

但是当我使用这段代码时

app.get('/orderinfo/:OrderCode', async (req, res) => {

   OrderCode = req.params.OrderCode
   knex.select("*").from("orders").limit(1).where({ 'OrderCode': OrderCode })
      .then(function (orders) {

         for (var i in orders) {
            const products= knex.select("*")
               .from("orderdetails")
               .where({ 'OrderId': orders[i].OrderId }).then(function (product) {
                  //console.log(product)
                  orders[i]['OrderDetails'] = product;
               })
         }
         res.json(orders); return;
      }).catch(function (err) {
         console.log(err);
         var result = {};
         result["error"] = true;
         result['errormsg'] = err;
         res.json(result);
      })

})

唯一的回应是

{
  "OrderId": 1001,
  "CustomerId": 1,
  "OrderDate": "2021-09-30T20:00:55.000Z",
  "OrderPrice": 99.8,
  "OrderStatus": 4,
  "OrderStatusDescription": "Shipped"
}

我能怎么做?

标签: node.jssql-serverexpressknex.js

解决方案


推荐阅读