如何格式化此关联获取续集

How to format this association fetching sequelize

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

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

我的控制器

 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);
    },

也许您可以在没有关联但使用模型的情况下实现查询。

 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);
},

您仍然会在产品属性中获得 order.quantity 和 order.price 作为名称。

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);

如果您可以控制订单 and/or 产品对象,则可以添加自定义 toJSON 方法。您可以根据需要格式化 json 输出。 https://futurestud.io/tutorials/create-a-custom-tojson-function-in-node-js-and-javascript

如果您没有对象的控制权,可以制作一个函数来格式化订单。

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})); 

我更喜欢自定义 toJSON 方法。当然,这取决于对对象结构的访问。