diff --git a/src/repository/TreeRepository.ts b/src/repository/TreeRepository.ts index f15aad1f91..725a947a3d 100644 --- a/src/repository/TreeRepository.ts +++ b/src/repository/TreeRepository.ts @@ -33,7 +33,7 @@ export class TreeRepository extends Repository { const escapeAlias = (alias: string) => this.manager.connection.driver.escape(alias); const escapeColumn = (column: string) => this.manager.connection.driver.escape(column); const parentPropertyName = this.manager.connection.namingStrategy.joinColumnName( - this.metadata.treeParentRelation!.propertyName, "id" + this.metadata.treeParentRelation!.propertyName, this.metadata.primaryColumns[0].propertyName ); return this.createQueryBuilder("treeEntity") diff --git a/test/github-issues/6948/entity/Category.ts b/test/github-issues/6948/entity/Category.ts new file mode 100644 index 0000000000..66e7d15ef2 --- /dev/null +++ b/test/github-issues/6948/entity/Category.ts @@ -0,0 +1,17 @@ +import { Entity, PrimaryGeneratedColumn, Column, Tree, TreeParent, TreeChildren } from "../../../../src"; + +@Entity() +@Tree("materialized-path") +export class Category { + @PrimaryGeneratedColumn() + cat_id: number; + + @Column() + cat_name: string; + + @TreeParent() + cat_parent: Category; + + @TreeChildren({ cascade: true }) + cat_children: Category[]; +} diff --git a/test/github-issues/6948/issue-6948.ts b/test/github-issues/6948/issue-6948.ts new file mode 100644 index 0000000000..0891f1a187 --- /dev/null +++ b/test/github-issues/6948/issue-6948.ts @@ -0,0 +1,38 @@ +import "reflect-metadata"; +import { Category } from "./entity/Category"; +import { Connection } from "../../../src/connection/Connection"; +import { + closeTestingConnections, + createTestingConnections, + reloadTestingDatabases, +} from "../../../test/utils/test-utils"; + +describe("github issues > #6948 TreeRepository's findRoots query incorrectly when using a custom primary key", () => { + let connections: Connection[]; + before( + async () => + (connections = await createTestingConnections({ + entities: [Category], + })) + ); + beforeEach(() => reloadTestingDatabases(connections)); + after(() => closeTestingConnections(connections)); + + it("entity parent column should work with custom primary column names ", () => + Promise.all( + connections.map(async (connection) => { + const categoryRepository = connection.getTreeRepository( + Category + ); + await categoryRepository.save( + categoryRepository.create({ + cat_name: "Root node", + }) + ); + const rootNodes = await categoryRepository.findRoots(); + rootNodes[0].should.deep.include({ + cat_name: "Root node", + }); + }) + )); +});