Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
Cómo formatear esta asociación obteniendo una secuencia

Tengo una asociación muchos a muchos con dos tablas, productos y pedidos. En mi tabla dinámica guardo la identificación, la cantidad y el precio del producto. Cuando busco el producto, necesito el nombre de este producto, pero para obtener el nombre necesito entrar en la tabla de productos. La respuesta de mi devolución de búsqueda como esta

 { "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" } } ] }

pero necesito el json en este formato

 { "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" } ] }

mi controlador

 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); },
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Tal vez pueda implementar la consulta sin la asociación pero usando el modelo.

 async getOrder(req, res) { const { id } = req.params; const order = await Orders.findByPk(id, {include: [{ model: Product, attributes: ['name'], include: [{ association: "OrdersProducts", attributes:['quantity', 'price'], raw: true, }], }]}) if (!order) return res.status(404).send({ message: 'order ${`id`}' }) return res.json(order); },

Seguirá obteniendo order.quantity y order.price como nombre en product como propiedades.

about 4 years ago · Juan Pablo Isaza Report

0

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);
about 4 years ago · Juan Pablo Isaza Report

0

Si tiene control sobre el pedido y/o el objeto del producto, puede agregar un método JSON personalizado. Puede formatear la salida json como desee. https://futurestud.io/tutorials/create-a-custom-tojson-function-in-node-js-and-javascript

Si no tiene el control del objeto, se podría hacer una función para formatear el pedido.

 const order = { "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" } } ]

};

 order.products = order.products.map(({OrdersProducts, ...other}) => ({...other, ...OrdersProducts}));

Prefiero métodos personalizados a JSON. Esto, por supuesto, depende del acceso a la estructura del objeto.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!