Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do recursion on typeorm relations

category.ts

@Entity('categoryenter code here')
export class Category{
  @PrimaryGeneratedColumn({ type: 'int' })
  id: Category;

  @OneToMany(() => Category, category => category.category,{eager:true})
  categoryList: Category[];

  @ManyToOne(() => Category, (category) => category.categoryList)
  category: Category;
}

The Category entity is above(mysql). I want to find a category with all it's children like this

await categoryRepo.findOne({
  where:{ id: 1 },
  relations:['categoryList']
})

But I got an error Maximum call stack size exceeded

What am I suppose to do

like image 397
Roach Avatar asked Aug 25 '26 09:08

Roach


1 Answers

Actually, as I see, you are trying to make a tree data structure. TypeORM has some decorators for that. Here is an example:

import {
  Entity, BaseEntity, Column,
  PrimaryGeneratedColumn, Tree,
  TreeParent, TreeChildren
} from 'typeorm';

@Tree('materialized-path')
@Entity({ name: 'Menu' })
export class Category extends BaseEntity {
  @PrimaryGeneratedColumn({ type: 'int' })
  id: number;

  @Column({ type: 'varchar', length: 50 })
  text: string;

  // Check bellow
  @TreeParent()
  parent: Category;

  @TreeChildren()
  children: Category[];
}

The decorator @Tree() is used to tell to TypeORM that every Instance has self references for itself. Every item should have one parent, and should have several children. The ancestors and descendant can be setted with the decorators @TreeParent() and @TreeChildren() respectively. Check the documentation for more details about the different modes available for @Tree() decorator.

like image 82
SleepWritten Avatar answered Aug 28 '26 04:08

SleepWritten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!