Return a nested object after joining a TreeRepository instead of an one-dimensional array

Viewed 124

I have two entities. 1: branches, self-referencing, 2: branchToLanguage.

There is a function getTree() that should return a nested object with the tree structure of the complete branch table and a property translation from brach_to_language table.

What I have is a function returning a one-dimensional array with all branch entities with the matching translation.

my function

 async getTree(branchId) {
    let branchTree = await this.connection
      .getTreeRepository(Branch)
      .createQueryBuilder('branch')
      .innerJoin("branch.branchId", "branchToLanguage")      
      .getMany()

    return branchTree;
  }

The Business Sector entity looks like this:

@Entity() 
@Tree("closure-table")
export class Branch {
    @PrimaryColumn()
    branchId: string;

    @Column()
    defaultName: string;
    
    @TreeParent()
    parent?: Branch;

    @TreeChildren({ cascade: true })
    children?: Branch[];

    @OneToMany(
        () => BranchToLanguage, 
        branchToLanguage => branchToLanguage.branch
    )
    translations: BranchToLanguage[]

    @BeforeInsert()
    private beforeInsert() {
        this.branchId = ulid();
    }
}

The BranchToLanguage entity like this:

@Entity()
export class BranchToLanguage {
    @PrimaryColumn()
    branchToLanguageId: string;
    
    @ManyToOne(
        () => Branch, 
        branch => branch.translations
    )
    @JoinColumn({ name: 'branchId' })
    branch: Branch;

    @ManyToOne(
        () => Language, 
        language => language.branchToLanguages
    )
    @JoinColumn({ name: "languageId" })
    language: Language;

    @Column()
    translation?: string;

    @BeforeInsert()
    beforeInsert() {
        this.branchToLanguageId = ulid();
    }
}

This is my first post here on Stackoverflow. If I do something wrong, you are welcome to criticize.

0 Answers
Related