Skip to content

FindAndCountAll returns wrong count  #10239

Closed

Description

@yalamber

What are you doing?

I have two models with many to many association. Below are Client and user models which are associated through ClientUser model, I am trying to use findAndCountAll using ClientUser model, when I don't use distinct: true, I get wrong result may be as it counts all associated models but even if I do distinct: true I always get count 1 as it seems to be doing distinct in ClientUser.ClientId which is always 1 as i am trying to get all users in specific client id.

//clients model
module.exports = (sequelize, DataTypes) => {
  let Client = sequelize.define('Client', {
    clientId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    name: { type: DataTypes.STRING(255), allowNull: false },
  });
  Client.associate = (models) => {
    Client.belongsToMany(models.User, {
      through: models.ClientUser,
      as: 'users',
      foreignKey: 'clientId',
      otherKey: 'userId'
    });
  };
  return Client;
}
//user model
module.exports = (sequelize, DataTypes) => {
  let User = sequelize.define('User', {
    userId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    username: {
      type: DataTypes.STRING(255), unique: true, validate: {
        min: 3,
        max: 30,
        is: /^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,30}$/i
      }
    },
    password: {
      type: DataTypes.STRING(255),
      validate: {
        min: 6
      }
    },
  }, {
      defaultScope: {
        attributes: { exclude: ['password'] },
      }
    });
  User.associate = (models) => {
    User.belongsToMany(models.Client, {
      through: models.ClientUser,
      as: 'clients',
      foreignKey: 'userId',
      otherKey: 'clientId'
    });
  };
  return User;
}
//client user
module.exports = (sequelize, DataTypes) => {
    let ClientUser = sequelize.define('ClientUser', {
      status: {
        type: DataTypes.ENUM,
        values: ['active', 'inactive']
      }
    });
    ClientUser.associate = (models) => {
      ClientUser.belongsTo(models.Client, {as: 'client', foreignKey: 'clientId'});
      ClientUser.belongsTo(models.User, {as: 'user', foreignKey: 'userId'});
    };
    return ClientUser;
}
//query here
let params = {
    include: [{
      model: User,
      as: 'user',
    }],
    where: {
       clientId: 1
    },
    distinct: true
};
let result = await ClientUser.findAndCountAll(params);

What do you expect to happen?

I expect the correct result with correct count.

What is actually happening?

produces wrong count.
without distinct: true

SELECT count(`ClientUser`.`clientId`) AS `count` FROM `ClientUsers` AS `ClientUser` LEFT OUTER JOIN `Users` AS `user` ON `ClientUser`.`userId` = `user`.`userId` LEFT OUTER JOIN `ContactInformations` AS `user->contactInformation` ON `user`.`userId` = `user->contactInformation`.`userId` LEFT OUTER JOIN `InstantMessengerInfos` AS `user->instantMessengerInfos` ON `user`.`userId` = `user->instantMessengerInfos`.`userId` LEFT OUTER JOIN `Roles` AS `role` ON `ClientUser`.`roleId` = `role`.`roleId` WHERE `ClientUser`.`clientId` = '1';

with distinct: true

 SELECT count(DISTINCT(`ClientUser`.`clientId`)) AS `count` FROM `ClientUsers` AS `ClientUser` LEFT OUTER JOIN `Users` AS `user` ON `ClientUser`.`userId` = `user`.`userId` LEFT OUTER JOIN `ContactInformations` AS `user->contactInformation` ON `user`.`userId` = `user->contactInformation`.`userId` LEFT OUTER JOIN `InstantMessengerInfos` AS `user->instantMessengerInfos` ON `user`.`userId` = `user->instantMessengerInfos`.`userId`
LEFT OUTER JOIN `Roles` AS `role` ON `ClientUser`.`roleId` = `role`.`roleId` WHERE `ClientUser`.`clientId` = '1';

Dialect: mysql
Dialect version: 1.6.4
Database version: 5.7.24
Sequelize version: 4.41.2
Tested with latest release: Yes 4.41.2 (If yes, specify that version)

Activity

  1. leogoesger commented on Dec 8, 2018

    @leogoesger

    Seeing the same issue with count. Current work around

    return this.Restaurant.findAndCount({
          ...pagePL,
          distinct: true,
          include: [{ model: Application, as: 'application' }]
        }).then(d => ({ ...d, rows: uniqBy(d.rows, 'id') }));
    
  2. rmoura-92 commented on Dec 27, 2018

    @rmoura-92

    same issue here.
    very annoying any group by query is returning count as like [{count: '1'}, {count: '1'}, {count: '1'}]

  3. MatthewHerbst commented on Jan 2, 2019

    @MatthewHerbst

    Possibly related: #9481 and #9669

  4. Alexsey commented on Jan 16, 2019

    @Alexsey
    Contributor

    The first issue on this #9109

  5. stale commented on Apr 16, 2019

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

  6. MatthewHerbst commented on Apr 16, 2019

    @MatthewHerbst

    This is not a stale issue, and in fact (imho) is one of Sequelize's most egregious bugs.

  7. stale commented on Jul 15, 2019

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

  8. MatthewHerbst commented on Jul 15, 2019

    @MatthewHerbst

    This is not a stale issue.

  9. papb commented on Jul 25, 2019

    @papb
    Member

    Is this an issue only with MySQL or does it happen with another dialect too?

  10. added
    status: awaiting response
    type: bug
    on Jul 25, 2019
  11. papb commented on Jul 30, 2019

    @papb
    Member

    Duplicate of #9109

  12. removed
    status: awaiting response
    on Jul 30, 2019
  13. added
    topic: count
    on Nov 2, 2019
  14. faraz9x commented on Jan 24, 2022

    @faraz9x

    distinct: true works but remember, your query must include an @Index column

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: counttype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions