如何通过 sequelize 获得不同的计数? [英] How to get a distinct count with sequelize?

查看:31
本文介绍了如何通过 sequelize 获得不同的计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 sequelize 获取特定列的不同计数.我最初的尝试是使用我的模型的计数"方法,但看起来这不可能.

I am trying to get a distinct count of a particular column using sequelize. My initial attempt is using the 'count' method of my model, however it doesn't look like this is possible.

需要 DISTINCT 功能,因为我要加入其他表并根据相关表过滤父级的行.

The DISTINCT feature is needed because I am joining other tables and filtering the rows of the parent based on the related tables.

这是我想要的查询:

SELECT COUNT(DISTINCT Product.id) as `count` 
FROM `Product` 
LEFT OUTER JOIN `Vendor` AS `vendor` ON `vendor`.`id` = `Product`.`vendorId` 
WHERE (`vendor`.`isEnabled`=true );

对我的产品模型使用以下查询:

using the following query against my Product model:

Product.count({
        include: [{model: models.Vendor, as: 'vendor'}],
        where: [{ 'vendor.isEnabled' : true }]
    })

生成以下查询:

SELECT COUNT(*) as `count` 
FROM `Product` 
LEFT OUTER JOIN `Vendor` AS `vendor` ON `vendor`.`id` = `Product`.`vendorId` 
WHERE (`vendor`.`isEnabled`=true );

推荐答案

现在 Sequelize 版本 1.7.0+ 似乎支持此功能.

Looks like this is now supported in Sequelize versions 1.7.0+.

模型的 countfindAndCountAll 方法将为您提供父模型的真实"或不同"计数.

the count and findAndCountAll methods of a model will give you 'real' or 'distinct' count of your parent model.

这篇关于如何通过 sequelize 获得不同的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆