Skip to content

BelongsToMany + Grouping + Counting seems to be broken #6711

Open

Description

@eikaramba

What you are doing?

Given a nxm association between Kingdom and Animals(picking up the test taxology here), i want to get all Kingdoms and count the animals in them. Should work as of #6297

describe('group and count in mxn association', function () {

        beforeEach(function () {
          this.Animal = this.sequelize.define('Animal', {
            name: Sequelize.STRING,
            age: Sequelize.INTEGER
          }});
          this.Kingdom = this.sequelize.define('Kingdom', {
            name: Sequelize.STRING
          });
          this.AnimalKingdom = this.sequelize.define('AnimalKingdom', {
            id: {
              type: Sequelize.INTEGER,
              primaryKey: true,
              autoIncrement: true
            },
            relation: Sequelize.STRING,
            mutation: Sequelize.BOOLEAN
          });

          this.Kingdom.belongsToMany(this.Animal, { through: { model: this.AnimalKingdom} });
          this.Animal.belongsToMany(this.Kingdom, { through: { model: this.AnimalKingdom} });

          return this.sequelize.sync({ force: true })
            .then(() => Sequelize.Promise.all([
              this.Animal.create({ name: 'Dog', age: 20 }),
              this.Animal.create({ name: 'Cat', age: 30 }),
              this.Animal.create({ name: 'Peacock', age: 25 }),
              this.Animal.create({ name: 'Fish', age: 100 })
            ]))
            .spread((a1, a2, a3, a4) => Sequelize.Promise.all([
                this.Kingdom.create({ name: 'Earth' }),
                this.Kingdom.create({ name: 'Water' }),
                this.Kingdom.create({ name: 'Wind' }),
                this.Kingdom.create({ name: 'Space' })
              ]).spread((k1, k2, k3, k4) => (
                Sequelize.Promise.all([
                  k1.addAnimals([a1, a2]),
                  k2.addAnimals([a4]),
                  k3.addAnimals([a3])
                ])
            )));
        });

        it('kingdom', function () {
          return this.Kingdom.findAll({
            group : ['Kingdom.id'],
            attributes: ['Kingdom.id', [Sequelize.fn('COUNT', Sequelize.col('Animals.id')), 'AnimalCount']],
            include:[{
              model: this.Animal,
              attributes: [],
              through: {
                attributes: []
              },
              duplicating:false
            }]
          }).then((kingdoms) => {
            console.log(kingdoms);
            kingdoms.forEach((kingdom) => {
              expect(kingdom.dataValues.AnimalCount).to.exist;
              expect(kingdom.dataValues.Animals).to.not.exist;
            });
          });
        });
      });

What do you expect to happen?

SELECT "Kingdom"."id", COUNT("Animals"."id") AS "AnimalCount"

FROM "Kingdoms" AS "Kingdom" LEFT OUTER JOIN ( "AnimalKingdoms" AS "Animals->AnimalKingdom" INNER JOIN "Animals" AS "Animals" ON "Animals"."id" = "Animals->AnimalKingdom"."AnimalId") ON "Kingdom"."id" = "Animals->AnimalKingdom"."KingdomId" GROUP BY "Kingdom"."id";

What is actually happening?

Error: Column »Animals->AnimalKingdom.id« needs to be used in the GROUP-BY-clause or in a aggregate function.

SELECT "Kingdom"."id", COUNT("Animals"."id") AS "AnimalCount",

//Too much attributes, breaks the sql
"Animals->AnimalKingdom"."id" AS "Animals.AnimalKingdom.id", "Animals->AnimalKingdom"."relation" AS "Animals.AnimalKingdom.relation", "Animals->AnimalKingdom"."mutation" AS "Animals.AnimalKingdom.mutation", "Animals->AnimalKingdom"."createdAt" AS "Animals.AnimalKingdom.createdAt", "Animals->AnimalKingdom"."updatedAt" AS "Animals.AnimalKingdom.updatedAt", "Animals->AnimalKingdom"."KingdomId" AS "Animals.AnimalKingdom.KingdomId", "Animals->AnimalKingdom"."AnimalId" AS "Animals.AnimalKingdom.AnimalId"

FROM "Kingdoms" AS "Kingdom" LEFT OUTER JOIN ( "AnimalKingdoms" AS "Animals->AnimalKingdom" INNER JOIN "Animals" AS "Animals" ON "Animals"."id" = "Animals->AnimalKingdom"."AnimalId") ON "Kingdom"."id" = "Animals->AnimalKingdom"."KingdomId" GROUP BY "Kingdom"."id";

I already tried nearly every possible combination of methods, attributes etc. But since 2 weeks i have no luck. However i got some results(see next comments)

Dialect: postgres
Database version:9.6
Sequelize version: 4.0.0-2 (3.x does not work too)

Activity

  1. eikaramba commented on Oct 16, 2016

    @eikaramba
    Author

    after digging through the sourcecode i found here (https://github.com/sequelize/sequelize/blob/master/lib/dialects/abstract/query-generator.js#L1350) if i set includeIgnoreAttributes:false, he is not including the attributes from the relation. So:

    it('kingdom', function () {
              return this.Kingdom.findAll({
                group : ['Kingdom.id'],
                attributes: [[Sequelize.fn('COUNT', Sequelize.col('Animals.id')), 'AnimalCount']],
          includeIgnoreAttributes:false,
                include:[{
                  model: this.Animal,
                  attributes: [],
                  through: {
                    attributes: []
                  },
                  duplicating:false
                }]
              }).then((kingdoms) => {
                console.log(kingdoms);
                kingdoms.forEach((kingdom) => {
                  expect(kingdom.dataValues.AnimalCount).to.exist;
                  expect(kingdom.dataValues.Animals).to.not.exist;
                });
              });
            });
    

    Unfortunately he is also not including any attribute apart from the count aggregate. But if i manually include my wanted attributes into the attributes list, i have what i want.

    Still i'm not sure if this is the expected behaviour and thus i wanted to leave this here to either make it easier to do queries like that in the future by fixing it or at least give users like me the tip into the right direction how to do this.

  2. idrisadetunmbi commented on Jul 28, 2018

    @idrisadetunmbi

    This thing has never worked for me despite all the solutions and combinations I have tried
    I keep getting different errors, most significantly
    "invalid reference to FROM-clause entry for table \"contents_users_views\""

    const contents = await models.content.findAll({
      attributes: {
        include: [
           [models.Sequelize.fn('COUNT', models.Sequelize.col('contents_users_views.userId')), 'no_viewers']
        ]},
        include: [{
            model: models.User,
            as: 'viewers',
            attributes: []
         }]
    

    Can someone help out with what the correct construct looks like to retrieve the count of an association in a belongsToMany relationship

  3. jordan-mcrae commented on Dec 17, 2019

    @jordan-mcrae

    @idrisadetunmbi I was pulling my hair out trying to figure this out. This is what I ended up doing:

    const categories = await CategoriesModel.findAll({
        include : [
          { model: models.Libraries, attributes: [] },
        ],
        attributes : {
          include: ['Categories.id', [Sequelize.fn('COUNT', Sequelize.col('Libraries.id')), 'LibraryCount']]
        },
        group : ['Categories.id'],
        includeIgnoreAttributes : false,
        distinct : true
      });
    

    For anyone reading this, my relationship is Categories belongsToMany Libraries, and Libraries BelongsToMany Categories. I wanted a simple count of how many Libraries a Category has.

    The key to getting this to work was adding includeIgnoreAttributes : false. Hope this helps someone else!

  4. added a commit that references this issue on Jan 16, 2020
  5. reopened this on Jan 16, 2020
  6. papb commented on Jan 16, 2020

    @papb
    Member
  7. added
    existing workaround
    Great SSCCE
    topic: count
    topic: group & order
    type: bug
    on Jan 16, 2020
  8. 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

    Great SSCCEexisting workaroundtopic: counttopic: group & ordertype: bug

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions