Skip to content

findAndCountAll with m:n association include count result is wrong #9669

Closed

Description

I have two models with m:n association:

 class Model1 extends sequelize.Model {
    static associate(models) {
      Model1.belongsTo(models.OneToOneModel, { foreignKey: 'oneToOneId', as: 'oneToOne' });

      Model1.belongsToMany(models.Model2, {
        through: {
          model: models.AssocModel,
          unique: false,
        },
        foreignKey: 'model1Id',
        constraints: false,
        as: 'models2',
      });
    }
  }

Model1.init({ /* code here */}, {
    // code here
    scopes: {
      withOneToOne() {
        return {
          include: {
            association: Model1.associations.oneToOne,
            where: { field: 'value' },
            require: true,
          },
        };
      },
      withModel2() {
        return {
          include: {
            association: Model1.associations.models2,
          },
        };
      },
    },

});
 class Model2 extends sequelize.Model {
    static associate(models) {
      Model2.belongsToMany(models.Model1, {
        through: {
          model: models.AssocModel,
          unique: false,
        },
        foreignKey: 'model2Id',
        constraints: false,
        as: 'models1',
      });
    }
  }

I'm trying to make following query:

Model1.scope(['withOneToOne', 'withModel2']).findAndCountAll({
    where: {},
    order: [ [ 'createdAt', 'DESC' ],
    limit: 20,
    offset: 0 ,
    distinct: true,
    // distinct: 'Model1.id', I also tried this
   //  If i avoid `distinct` option, 
   // count will be wrong, due to `models2` different values with one `Model1`
});

I'm expecting following query

SELECT count(DISTINCT (`Model1`.id)) AS `count`
FROM `Model1` AS `Model1` INNER JOIN `OneToOneModel` AS `oneToOne`
    ON `Model1`.`oneToOnkeFk` = `oneToOne`.`id` AND `oneToOne`.`field` = 'value'
  LEFT OUTER JOIN (`AssocModel` AS `models2->AssocModel` INNER JOIN `Model2` AS `models2`
      ON `models2`.`id` = `models2->AssocModel`.`model2Id`)
    ON `Model1`.`id` = `models2->AssocModel`.`model2Id`;

But it gives me following query:

SELECT count(DISTINCT (*)) AS `count`
FROM `Model1` AS `Model1` INNER JOIN `OneToOneModel` AS `oneToOne`
    ON `Model1`.`oneToOnkeFk` = `oneToOne`.`id` AND `oneToOne`.`field` = 'value'
  LEFT OUTER JOIN (`AssocModel` AS `models2->AssocModel` INNER JOIN `Model2` AS `models2`
      ON `models2`.`id` = `models2->AssocModel`.`model2Id`)
    ON `Model1`.`id` = `models2->AssocModel`.`model2Id`;

And it naturally fails with

message: You have an error in your SQL syntax; check the manual that corresponds to your MySQL 
server version for the right syntax to use near '*)) AS `count` FROM `Model1` AS `Model1` INNER 
JOIN `OneToOneModel` AS `oneToOne`' at line 1, stack: SequelizeDatabaseError: You have an error in 
your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax 
to use near '*)) AS `count` FROM `Model1` AS `Model1` INNER JOIN `OneToOneModel` AS 
`oneToOne`' at line 1

So, in fact, we have two issues here:

  • distinct option does not work as expected
  • findAndCountAll does not work as expected with n:m assocciation

Dialect: mysql
Dialect version: 5
Sequelize version: 4.38.0

Activity

  1. stale commented on Oct 14, 2018

    @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 🙂

  2. NaifousBS commented on Oct 24, 2018

    @NaifousBS

    +1

  3. JamesMGreene commented on Mar 15, 2019

    @JamesMGreene

    Give this workaround a try:

    // Add a permanent global hook to prevent unknowingly hitting this Sequelize bug:
    //   https://github.com/sequelize/sequelize/issues/10557
    sequelize.addHook('beforeCount', function (options) {
      if (this._scope.include && this._scope.include.length > 0) {
        options.distinct = true
        options.col = this._scope.col || options.col || `"${this.options.name.singular}".id`
      }
    
      if (options.include && options.include.length > 0) {
        options.include = null
      }
    })
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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions