Skip to content

Commit

Permalink
fix: self referencing with through table where-clause
Browse files Browse the repository at this point in the history
  • Loading branch information
shawara committed Nov 17, 2023
1 parent 5bfbb99 commit 4228c62
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/dialects/abstract/query-generator.js
Expand Up @@ -2104,6 +2104,10 @@ https://github.com/sequelize/sequelize/discussions/15694`);
topInclude.association = undefined;

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({
Expand Down
57 changes: 57 additions & 0 deletions test/integration/associations/self.test.js
Expand Up @@ -143,4 +143,61 @@ describe(Support.getTestDialectTeaser('Self'), () => {
expect(count).to.be.equal(3);
expect(children.map(v => v.id)).to.have.members([this.mary.id]);
});

it('should be able to handle a where in include of self association with through table', async function() {
const Node = this.sequelize.define('Node', {
id: {
type: DataTypes.INTEGER,
primaryKey: true
}
}, {
tableName: 'node',
timestamps: false
});

const Edge = this.sequelize.define('Edge', {
child_id: {
type: DataTypes.INTEGER,
primaryKey: true
},
parent_id: {
type: DataTypes.INTEGER,
primaryKey: true
}
}, {
tableName: 'edge',
timestamps: false
});
Edge.belongsTo(Node, { foreignKey: 'parent_id' });
Edge.belongsTo(Node, { as: 'children', foreignKey: 'child_id' });
Node.belongsToMany(Node, { through: Edge, as: 'children', foreignKey: 'parent_id', otherKey: 'child_id' });

await this.sequelize.sync({ force: true });

const [parentNode, childNode] = await Promise.all([
Node.create({ id: 1 }),
Node.create({ id: 2 })
]);

await parentNode.setChildren([childNode]);

const result = await Node.findAll({
attributes: ['id'],
include: [
{
model: Node,
as: 'children',
attributes: ['id'],
where: {
id: childNode.id
},
jointype: 'inner'
}
],
limit: 20,
raw: true,
nest: true
});
expect(result).to.deep.equal([{ id: 1, children: { id: 2, Edge: { child_id: 2, parent_id: 1 } } }]);
});
});

0 comments on commit 4228c62

Please sign in to comment.