How to get a distinct count with sequelize?

前端 未结 4 2043
长发绾君心
长发绾君心 2021-02-12 02:27

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

4条回答
  •  情书的邮戳
    2021-02-12 03:16

    With respect to your question in order to get the distinct counts of products based on the id of product

    you just need to pass the key 'distinct' with value 'id' to your count object , Here is the example

    To generate this sql query as you asked

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

    Add 'distinct' key in your Sequelize query

    Product.count({
            include: [{model: models.Vendor, as: 'vendor'}],
            where: [{ 'vendor.isEnabled' : true }],
            distinct: 'id' // since count is applied on Product model and distinct is directly passed to its object so Product.id will be selected
        });
    

    This way of using 'distinct' key to filter out distinct counts or rows , I tested in Sequelize Version 6.

    Hope this will help you or somebody else!

提交回复
热议问题