How to get a distinct count with sequelize?

前端 未结 4 2101
长发绾君心
长发绾君心 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:08

    UPDATE: New version

    As mentioned in the comments, things have changed since my original post. There is now separate distinct and col options. The docs for distinct state:

    Apply COUNT(DISTINCT(col)) on primary key or on options.col.

    It appears, you now want something along the lines of:

    MyModel.count({
      include: ...,
      where: ...,
      distinct: true,
      col: 'Product.id'
    })
    .then(function(count) {
        // count is an integer
    });
    

    Original Post

    After looking at Model.count method in lib/model.js, and tracing some code, I found that when using Model.count, you can just add any kind of aggregate function arguments supported by MYSQL to your options object. The following code will give you the amount of different values in MyModel's someColumn:

    MyModel.count({distinct: 'someColumn', where: {...}})
    .then(function(count) {
        // count is an integer
    });
    

    That code effectively generates a query of this kind: SELECT COUNT(args) FROM MyModel WHERE ..., where args are all properties in the options object that are not reserved (such as DISTINCT, LIMIT and so on).

提交回复
热议问题