Выполнение подзапросов

#node.js #sequelize.js

#node.js #sequelize.js

Вопрос:

в этом случае я хочу найти общее время подготовки для каждого заказа в соответствии с идентификатором заказа, но когда я пишу так, он показывает только 1 результат, который является первым,

  let prepareOrder = await OrderItem.findAll({
          
    where: {
            options: null,
          },
    
          attributes: ["orderId"],
    
          include: [
            {
              model: Item,
              attributes: [
                [
                  sequelize.fn("sum", sequelize.col("prepareTime")),
                  "totalPrepareTime",
                ],
    
              ],
    
            },
          ],
        });
  

Ответ №1:

Вам нужно выполнить внешний запрос. SUM() Когда вы запускаете его во внутреннем запросе, он возвращает одну строку, а затем выполняет a JOIN , поэтому вы получаете только одну строку.

 const prepareOrder = await OrderItem.findAll({
  attributes: [
    "orderId",
    // get the summary at the OrderItem for each related Item
    [
      sequelize.fn("sum", sequelize.col("item.prepareTime")),
      "totalPrepareTime",
    ],
  ],
  // include Item but no attributes for performance
  include: {
    model: Item,
    attributes: [],
  },
  where: {
    options: null,
  },
});