繁体   English   中英

Sequelize - 基于包含条件的计数

[英]Sequelize - Count Based on Include Condition

我正在使用sequelize count函数如下:

定义:

const countAllOrdersWhere = async (conditions) =>
    Order.count({
        where: conditions,
    })
        .then((count) => ({ count, error: null }))
        .catch((error) => ({ count: null, error }));

用法:

  const { count, error: countError } = await countAllOrdersWhere({
                    [Op.or]: [
                        { userId: userIds, status },
                        { status, venueId },
                    ],
                });

这很好用,但是我现在需要添加一个基于关联模型的条件:

  1. 每个order都有许多与之关联的orderItemsorderItem表中的每一行都有一个orderId 。)
  2. 每个orderItem都有一个与之关联的item - ( orderItem表中的每一行都有一个itemid 。)

我有一个itemIds数组,我只想计算与 orderItem 关联的订单,该orderItemitemId在我的列表中。

查询orders时,我在findAll函数中执行此子句,方法是

include: [
 {
 model: OrderItem,   
 where: Sequelize.literal(
      itemIds && itemIds.length > 0
      ? `"orderItems"."itemId" IN (${itemIds})`
      : 'true'
 )}]

但是,我不确定如何在count函数中执行此操作

count方法还具有include选项,因此您可以像使用findAll一样使用它,请参阅count

const countAllOrdersWhere = async (conditions) =>
    Order.count({
        include: [
 {
   model: OrderItem,   
   // this option is important in order to get the correct result (leads to INNER JOIN
  // instead of LEFT OUTER JOIN)
   required: true,
   where: (itemIds && itemIds.length > 0) ? {
     itemId: {
      [Op.in]: itemIds
     }
   } : {}
  }]
  }).then((count) => ({ count, error: null }))
    .catch((error) => ({ count: null, error }));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM