[英]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 },
],
});
这很好用,但是我现在需要添加一个基于关联模型的条件:
order
都有许多与之关联的orderItems
( orderItem
表中的每一行都有一个orderId
。)orderItem
都有一个与之关联的item
- ( orderItem
表中的每一行都有一个itemid
。) 我有一个itemIds
数组,我只想计算与 orderItem 关联的订单,该orderItem
的itemId
在我的列表中。
查询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.