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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With