【发布时间】:2018-10-08 05:37:03
【问题描述】:
所以,我似乎在从 Node JS 中的 forEach MYSQL 查询循环返回一个值然后将其插入到 ejs 模板中时遇到问题。目前,这些是我的代码:
app.js GET 请求
app.get("/admin/stock", function(req, res) {
db.query("SELECT * FROM stock", function (err, stock) {
if (err) {
console.log("Error with showing SQL")
} else {
stock.forEach(function (stock) {
db.query("SELECT * FROM product WHERE productID = " +
stock.stock_productID, function (err, product) {
if (err) {
console.log("Error");
}
else {
stock.stock_productID = product[0].productName
}
});
db.query("SELECT * FROM currency WHERE currencyID = " +
stock.stock_currencyID, function (err, currency) {
if (err) {
console.log("Error");
}
else {
stock.stock_currencyID = currency[0].currencyName
}
});
db.query("SELECT * FROM customer WHERE customerID = " +
stock.stock_customerID, function (err, customer) {
if (err) {
console.log("Error");
}
else {
stock.stock_customerID =
customer[0].customerBusiness;
console.log(stock);
}
})
});
}
console.log(stock);
res.render("admin/stock", {stock:stock, userFName: req.user[1]})
})
});
股票页面 EJS
<table class="generalTable">
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Currency</th>
<th>Cost</th>
<th>Date Bought</th>
<th>Bought From</th>
</tr>
<% stock.forEach(function(stock){ %>
<tr>
<td><%=stock.stock_productID%></td>
<td><%=stock.quantityStockCurrent%></td>
<td><%=stock.stock_currencyID%></td>
<td><%=stock.priceBought%></td>
<td><%=stock.boughtDate%></td>
<td><%=stock.stock_customerID%></td>
</tr>
<% }) %>
</table>
stock 的第一个 console.log 显示替换的值,但是第二个显示原始数组值,因此页面加载时使用原始值(ID 等,而不是名称)。
如何将内部/编辑后的数组发送到 res.render 而不是原始数组?
非常感谢, 布拉德
编辑//////
通过使用 JOIN,输出是正确的
【问题讨论】:
-
您确实需要了解
LEFT JOIN和INNER JOIN如何在SQL 中工作。您的代码是从关系数据库中检索信息的最低效的方式。修复这个没有用,请阅读连接并重写您的查询。 -
非常感谢,我愚蠢地忘记了 JOIN!
标签: mysql arrays node.js foreach ejs