我有一个类似的应用程序。
app.get('/orders/:pizzeriaID/:status', async (req, res) => {
try {
const requestedOrderByPizzeriaID = req.params['pizzeriaID'];
const requestedOrderByStatus = req.params['status'];
console.log("STATUS" + requestedOrderByStatus);
const client = await pool.connect();
const result = await client.query('SELECT od.orderID, od.pizzaID, od.pizzaOrderQuantity, o.orderName, o.orderAddress, o.orderComment, o.orderPhone, o.orderEmail FROM ordersDetails od NATURAL JOIN pizzeria p NATURAL join orders o WHERE p.pizzeriaID=\'' + requestedOrderByPizzeriaID + '\' AND o.orderStatus=\'' + requestedOrderByStatus + '\'');
const results = (result) ? result.rows : null;
res.json({results});
client.release();
} catch (err) {
console.error(err);
res.send("Error " + err);
}});
在这样的数据库模型中: DBModel
它显示如下JSON:JSON1
我只想拥有一个orderid = 1的对象,其中有第二个json(array?),其中包含pizzaID和pizzaOrderQuantity列表。
需要这样的方式:
results:{
orderid: 1,
orderDetails: [{
pizzaid: 1,
pizzaorderquantity: 2,
},
pizzaid: 2,
pizzaorderquantity: 4,
},
pizzaid: 3,
pizzaorderquantity: 1,
}],
ordername: 'Karol Piwnicki',
orderaddress: 'Rydla 26/30',
ordercomment: 'Szybko poprosze',
orderphone: '111-222-333',
orderemail: 'mail@mail.com' }
我已经坐了一段时间了,尝试了教程和堆栈中发现的几种方法,但是没有运气。
任何帮助将不胜感激!
答案 0 :(得分:0)
您可以使用Javascript reduce函数对订单进行分组,然后使用Object.values将其转换回数组。
const json = Object.values(results.reduce((acc, order) => {
if (!acc[order.orderid]) {
acc[order.orderid] = {
orderid: order.orderid,
orderDetails: []
};
}
acc[order.orderid].orderDetails.push(order)
return acc
}, {}))
res.json(json);
[edit]刚刚编辑了代码段,因此输出将完全相同
答案 1 :(得分:0)
我通过在SQL查询中返回一个json并使用res.send()切换res.json()来解决了这个问题。
作为参考,我使用了这样的查询:
const result = await client.query('select row_to_json(x) AS order
FROM (select o.orderID, json_agg(json_build_object(\'pizzaID\',o.pizzaID, \'pizzaOrderQuantity\', o.pizzaOrderQuantity)) AS orderDetails,
ord.orderName, ord.orderAddress, ord.orderComment, ord.orderPhone, ord.orderEmail FROM ordersDetails o
NATURAL JOIN pizzeria p NATURAL JOIN orders ord
WHERE p.pizzeriaID=\'' + requestedOrderByPizzeriaID + '\' GROUP BY o.orderID, ord.orderName, ord.orderAddress, ord.orderComment, ord.orderPhone, ord.orderEmail) as x');
感谢尝试!