node.js - 在 foreach 循环中使用 knex 进行多链查询
问题描述
我是 node 和 knex 的新手,我在 mssql 上有名为“orders”、“orderdetails”和“customers”的表,看起来像
orders
- OrderId (int)
- 客户 ID(整数)
- 订单日期 (datetime2)
- 订单价格(货币)
- 订单状态(整数)
- OrderStatusDescription (varchar(50))
orderdetails
- OrderId (int)
- 产品 ID(整数)
- 产品名称 (varchar(255))
- 数量(整数)
- 价格(钱)
- 净额(金钱)
使用 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"
}
我能怎么做?
解决方案
推荐阅读
- ios - 动画后计算uiview的高度
- php - 更新查询正在更新每个新值并从数据库中删除以前更新的值
- python-3.x - 模型并行性不起作用?所有 GPU 都没有被使用?
- .net - 将 TLSv1 升级到 TLSv1_2016 后,通信 .NET 应用程序失败
- c++ - 从地址调用函数
- html - 为什么我的 animation-direction:alternate 不起作用?
- python - 为什么它不会将 `__get__` 转换为 `__get__.__get__`?
- gwt - 如何从 GWT 中的选定日期获取当前月份?
- php - 如何在 wordpress 中制作自定义搜索和过滤页面?
- javascript - React Router 阻止路由属性更新