Search code examples
javascripttypescriptormtypeormtypeorm-activerecord

How to join every child entity in a tree structure in typeorm


I have a tree structure of categories. Those categories have relations to other tables.

import {Entity, Column, PrimaryGeneratedColumn, ManyToOne, OneToMany} from "typeorm";
@Entity()
export class Category {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @Column()
    description: string;

    @ManyToOne(type => Category, category => category.children)
    parent: Category;

    @OneToMany(type => Category, category => category.parent)
    children: Category[];

    @OneToMany(type => Site, site => site.category)
    sites: Site[];
}

My code to get the tree:

console.log(await getConnection().getTreeRepository(Category).findTrees());

The result:

[
  Category {
    pk: 8,
    id: '1C606380-020A-4CED-8EBA-AA1C9C16FCF2',
    title: 'Category EXPLICIT',
    createdBy: 'SAFETYMANUAL',
    createdAt: 2021-07-27T19:57:03.213Z,       
    hidden: false,
    orderValue: 0,
    deletionDate: null,
    childCategories: [ [Category] ]
  }
]

I want to load the whole tree WITH the relations, in this case with the array of Sites. Setting eager to true doesn't change anything. I only get back the tree without the sites array. Is there a possibility to join in tree structures?


Solution

  • I implemented a pull request that enables loading relations for trees:

    const treeCategoriesWithRelations = await repository.findTrees({ relations: ["sites"] });
    // automatically joins the sites relation