gpt4 book ai didi

javascript - 如何格式化此关联获取 Sequelize

转载 作者:行者123 更新时间:2023-12-04 14:47:44 27 4
gpt4 key购买 nike

我有一个多对多的关联,有两个表,products 和 orders。在我的数据透视表中,我保存了产品的 ID、数量和价格。当我获取产品时,我需要该产品的名称,但要获取名称,我需要在产品表中获取。我获取返回的响应是这样的

{
"id": 111,
"name": "Matheus",
"phonenumber": "69993750103",
"reference": null,
"value_subtotal": "10.000",
"value_delivery": "5.000",
"value_total": "15.000",
"status": "pending",
"products": [
{
"name": "Açai 350ml",
"OrdersProducts": {
"quantity": 2,
"price": "0.000"
}
},
{
"name": "acai 350ml",
"OrdersProducts": {
"quantity": 3,
"price": "0.000"
}
}
]
}

但我需要这种格式的json

{
"id": 111,
"name": "Matheus",
"street": "Rua olavo bilac",
"phonenumber": "69993750103",
"number": "3511",
"reference": null,
"note": "Retirar o morango",
"value_subtotal": "10.000",
"value_delivery": "5.000",
"value_total": "15.000",
"status": "pending",
"createdAt": "2021-10-20T18:26:25.000Z",
"updatedAt": "2021-10-20T18:26:25.000Z",
"products": [
{
"name": "Açai 350ml",
// here the difference, i want create a single object in the return, with all data i need of the product
"quantity": 2,
"price": "0.000"
}
},
{
"name": "acai 350ml",
"quantity": 3,
"price": "0.000"

}
]
}

我的 Controller

 async getOrder(req, res) {
const { id } = req.params;

const order = await Orders.findByPk(id, {include: [{
association: 'products',
attributes: ['name'],
through: {
attributes:['quantity', 'price'],


},
raw: true,
}]})
if (!order) return res.status(404).send({ message: 'order ${`id`}' })
return res.json(order);
},

最佳答案

var a = {
"id": 111,
"name": "Matheus",
"phonenumber": "69993750103",
"reference": null,
"value_subtotal": "10.000",
"value_delivery": "5.000",
"value_total": "15.000",
"status": "pending",
"products": [{
"name": "Açai 350ml",
"OrdersProducts": {
"quantity": 2,
"price": "0.000"
}
},
{
"name": "acai 350ml",
"OrdersProducts": {
"quantity": 3,
"price": "0.000"
}
}
]
};

var orders = [];
orders.push(a);

var updatedOrders = orders.map(function(order) {
order.products.forEach(function(product) {
product.price = product.OrdersProducts.price;
product.quantity = product.OrdersProducts.quantity;
delete product.OrdersProducts;
});
return order;
});
console.log(updatedOrders);

关于javascript - 如何格式化此关联获取 Sequelize ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69710076/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com