Skip to content

Self referencing with through table not working correctly. #16719

Open

Description

@shawara

Issue Creation Checklist

  • I understand that my issue will be automatically closed if I don't fill in the requested information
  • I have read the contribution guidelines

Bug Description

Having a self-referencing model with through model
Trying to query Model X with include model X returns wrong result because of top parent name in the where-clause clash with the included models

Reproducible Example

Steps to reproduce

  1. create two models Nodes, Edges:
module.exports = function (sequelize) {
  var Edge = sequelize.define('edge', {}, { tableName: 'Edges' });
  Edge.associate = function (models) {
    Edge.belongsTo(models.Node, { foreignKey: 'parent_id' });
    Edge.belongsTo(models.Node, { as: 'children', foreignKey: 'child_id' });
  };
  return Edge;
};
const Sequelize = require('sequelize');

module.exports = function (sequelize) {
  const Node = sequelize.define(
    'node',
    {
      id: { type: Sequelize.UUID, primaryKey: true, validate: { isUUID: 4 } },
    },
    { tableName: 'Nodes' }
  );

  Node.associate = function (models) {
    Node.belongsToMany(Node, { through: models.Edge, as: 'children', foreignKey: 'parent_id', otherKey: 'child_id' });
  };

  return Node;
};
  1. Insert sample data:
INSERT INTO "Nodes" (id) VALUES ('82f62093-d2eb-4719-b877-111111111111');
INSERT INTO "Nodes" (id) VALUES ('82f62093-d2eb-4719-b877-222222222222');
---
INSERT INTO "Edges" (parent_id, child_id) VALUES ( '82f62093-d2eb-4719-b877-111111111111', '82f62093-d2eb-4719-b877-222222222222');
  1. Run a query to find nodes include node as children
const nodes = await models.Node.findAll({
    attributes: ['id'],
    include: [
      {
        model: models.Node,
        as: 'children',
        attributes: ['id'],
        where: {
          id: '82f62093-d2eb-4719-b877-222222222222',
        },
        jointype: 'inner',
      },
    ],
    limit: 100,
  }
);

What do you expect to happen?

it should return

[{
  id: '82f62093-d2eb-4719-b877-111111111111',
  children: {
    id: '82f62093-d2eb-4719-b877-222222222222',
    edge: {
      parent_id: '82f62093-d2eb-4719-b877-111111111111',
      child_id: '82f62093-d2eb-4719-b877-222222222222'
    }
  }
}]

What is actually happening?

it did return an empty result

[]

Here is the generated query:

SELECT "node".*,
       "children"."id"              AS "children.id",
       "children->edge"."parent_id" AS "children.edge.parent_id",
       "children->edge"."child_id"  AS "children.edge.child_id"
FROM (SELECT "node"."id"
      FROM "Nodes" AS "node"
      WHERE (SELECT "edge"."parent_id"
             FROM "Edges" AS "edge"
                      INNER JOIN "Nodes" AS "node" ON "edge"."child_id" = "node"."id" AND
                                                      "node"."id" = '82f62093-d2eb-4719-b877-222222222222'
             WHERE ("node"."id" = "edge"."parent_id")
             LIMIT 1) IS NOT NULL
      LIMIT 100) AS "node"
         INNER JOIN ("Edges" AS "children->edge" INNER JOIN "Nodes" AS "children"
                     ON "children"."id" = "children->edge"."child_id") ON "node"."id" = "children->edge"."parent_id" AND
                                                                          "children"."id" =
                                                                          '82f62093-d2eb-4719-b877-222222222222';

Environment

  • Sequelize version: 6.34.0
  • Node.js version: 18
  • If TypeScript related: TypeScript version:
  • Database & Version: postgres:11.11
  • Connector library & Version: "pg": "8.11.3"

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I will need guidance.
  • No, I don't have the time, but my company or I are supporting Sequelize through donations on OpenCollective.
  • No, I don't have the time, and I understand that I will need to wait until someone from the community or maintainers is interested in resolving my issue.

Indicate your interest in the resolution of this issue by adding the 👍 reaction. Comments such as "+1" will be removed.

Activity

  1. added
    pending-approval
    type: bug
    on Nov 3, 2023
  2. shawara commented on Mar 8, 2024

    @shawara
    Author

    I used patch-package to patch [email protected] for the project I'm working on.

    Here is the diff that solved my problem:

    diff --git a/node_modules/sequelize/lib/dialects/abstract/query-generator.js b/node_modules/sequelize/lib/dialects/abstract/query-generator.js
    index 7101680..101c4bf 100644
    --- a/node_modules/sequelize/lib/dialects/abstract/query-generator.js
    +++ b/node_modules/sequelize/lib/dialects/abstract/query-generator.js
    @@ -1485,6 +1485,10 @@ https://github.com/sequelize/sequelize/discussions/15694`);
         const topAssociation = topInclude.association;
         topInclude.association = void 0;
         if (topInclude.through && Object(topInclude.through.model) === topInclude.through.model) {
    +      if (topAssociation.toTarget !== undefined && topParent.model.name === topAssociation.toTarget.as) {
    +        topAssociation.toTarget.as = `${topInclude.through.model.name}->${topAssociation.toTarget.as}`;
    +      }
    +      
           query = this.selectQuery(topInclude.through.model.getTableName(), {
             attributes: [topInclude.through.model.primaryKeyField],
             include: Model._validateIncludedElements({

    This body was partially generated by patch-package.

  3. added theissue type on Mar 9, 2025
  4. removed
    type: bug
    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

    pending-approval

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions