Skip to content

No multiple includes possible when using count function #8416

Open

Description

@JasperTack

In my domain model I have the following three models:

var challenge = sequelize.define('Challenge', {
    challengeId: {
        field: 'challenge_id',
        type: DataTypes.INTEGER,
        primaryKey: true,
        allowNull: false,
        autoIncrement: true,
        unique: true
    },
    ownerId: {
        type: DataTypes.INTEGER,
        references: { model: 'USER', key: 'user_id'},
        allowNull: false
    },
    description: {
        field: 'description',
        type: DataTypes.TEXT,
        allowNull: false
    }
};

challenge.belongsTo(models.User, {foreignKey: 'ownerId'});
challenge.hasMany(models.Idea, {foreignKey: 'challengeId'});

var idea = sequelize.define('Idea', {
  ideaId: {
    field: 'idea_id',
    type: DataTypes.INTEGER,
    primaryKey: true,
    allowNull: false,
    autoIncrement: true,
    unique: true
  },
  challengeId: {
    field: 'challenge_id',
    type: DataTypes.INTEGER,
    references: { model: 'CHALLENGE', key: 'challenge_id'},
    allowNull: true
  },
  description: {
    field: 'description',
    type: DataTypes.STRING(600),
    allowNull: false
  }
};
idea.belongsTo(models.Challenge, {foreignKey: 'challengeId'});

var user = sequelize.define('User', {
  userId: {
    field: 'user_id',
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    unique: true
  },
  name: {
    field: 'name',
    type: DataTypes.STRING,
    allowNull: false
  }
}
user.hasMany(models.Challenge, {foreignKey: 'ownerId'});

This represents a simple domain model where a challenge is owned by a specific user. An idea is linked to one or zero challenges.

Now I would like to search for all challenges and also add a count of how many ideas are associated with that challenge. This query is something i got working, but as soon as i also want to include userinformation, the joins in the generated SQL are not correct.

To query the challenges and get a count of ideas I do this:

models.Challenge.findAll({
   attributes: ["Challenge.*", [models.sequelize.fn('COUNT', models.sequelize.col('Ideas.idea_id')), 'IdeaCount']],
   include: [{
      model: models.Idea,
      attributes: []
   }],
   group: ["Challenge.challenge_id"],
   order: [['count', 'ASC']]
}).then(function (rows) {
   console.log(rows)
 });

Which executes the correct SQL query:

SELECT "Challenge"."challenge_id" AS "challengeId", 
      "Challenge".*, 
       COUNT("Ideas"."idea_id")   AS "IdeaCount" 
FROM   "CHALLENGE" AS "Challenge" 
       LEFT OUTER JOIN "IDEA" AS "Ideas" 
                    ON "Challenge"."challenge_id" = "Ideas"."challenge_id" 
WHERE  "Challenge"."company_id" = 1 
GROUP  BY "Challenge"."challenge_id" 
ORDER  BY "createdAt" DESC; 

Now when I want to also include information from the creator of the challenges, i get the wrong SQL.

models.Challenge.findAll({
   attributes: ["Challenge.*", [models.sequelize.fn('COUNT', models.sequelize.col('Ideas.idea_id')), 'IdeaCount']],
   include: [{
      model: models.Idea,
      attributes: []
   },
   {
      model: models.User,
      attributes: ["userId", "name"]
   }],
   group: ["Challenge.challenge_id"],
   order: [['count', 'ASC']]
}).then(function (rows) {
   console.log(rows)
 });

Which results in the following SQL:

SELECT "Challenge".*, 
    COUNT("Ideas"."idea_id") AS "IdeaCount", 
       "User".*
FROM   "CHALLENGE" AS "Challenge" 
       LEFT OUTER JOIN "IDEA" AS "Ideas" 
                    ON "Challenge"."challenge_id" = "Ideas"."challenge_id" 
       INNER JOIN "USER" AS "User" 
               ON "Challenge"."ownerId" = "User"."user_id" 
       LEFT OUTER JOIN ("USER_ROLE" AS "User.Roles.USER_ROLE" 
                        INNER JOIN "ROLE" AS "User.Roles" 
                                ON "User.Roles"."role_id" = 
                                   "User.Roles.USER_ROLE"."feature_id") 
                    ON "User"."user_id" = "User.Roles.USER_ROLE"."user_id" 
WHERE  "Challenge"."company_id" = 1 
GROUP  BY "Challenge"."challenge_id" 
LIMIT  20;

Instead I would need an SQL query like this:

SELECT "Challenge".*, 
   "User"."user_id", 
   "User"."firstname", 
   "User"."lastname" 
FROM   (SELECT "Challenge".*, 
               COUNT("Ideas"."idea_id") AS "IdeaCount" 
        FROM   "CHALLENGE" AS "Challenge" 
               LEFT OUTER JOIN "IDEA" AS "Ideas" 
                            ON "Challenge"."challenge_id" = 
                               "Ideas"."challenge_id" 
        WHERE  "Challenge"."company_id" = 1 
        GROUP  BY "Challenge"."challenge_id") AS "Challenge" 
       LEFT OUTER JOIN "USER" AS "User" 
                    ON "User"."user_id" = "Challenge"."ownerId" 
ORDER  BY "createdAt" DESC 
LIMIT  20; 

It seems like sequelize puts the left outer join for the user on the same level as the one that is used for counting the assocations. Instead, the join for the user information should happen outside of it. Is it possible to influence sequelize in such a way that this joins is done separately like is done as in the SQL statement described above?

Activity

  1. stale commented on Jan 1, 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. popra commented on Aug 17, 2018

    @popra

    This is still an issue

  3. MaartenGe commented on Feb 5, 2019

    @MaartenGe

    I'm currently having the same issue where I'd like to count 2 many to many associations and no multiple includes are possible

  4. davehowson commented on Dec 31, 2019

    @davehowson

    Still an issue

  5. reopened this on Jan 16, 2020
  6. added
    topic: count
    type: bug
    on Jan 16, 2020
  7. deleteeeeeeeeeeeed commented on Feb 27, 2020

    @deleteeeeeeeeeeeed

    still issueeeee
    i can not count it

  8. dobrovolskaa commented on Apr 5, 2021

    @dobrovolskaa

    still an issue :c

  9. karimmakram commented on Jun 18, 2022

    @karimmakram

    still an issue
    but you can solve count with DISTINCT
    [models.sequelize.fn('COUNT',models.sequelize.fn('DISTINCT' models.sequelize.col('Ideas.idea_id'))), 'IdeaCount']
    but other operation like sum still duplicate data

  10. abdukulov-talgat commented on Oct 30, 2022

    @abdukulov-talgat

    Same issue here.

  11. added theissue type on Mar 9, 2025
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

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions