【问题标题】:How to do recursion on typeorm relations如何对 typeorm 关系进行递归
【发布时间】:2021-06-24 16:02:01
【问题描述】:

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;
}

Category 实体在上面(mysql)。 我想找到一个像这样的所有孩子的类别

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

但是我收到了一个错误Maximum call stack size exceeded

我想做什么

【问题讨论】:

    标签: node.js typescript nestjs typeorm


    【解决方案1】:

    实际上,正如我所见,您正在尝试制作一个树形数据结构。 TypeORM 有一些装饰器。这是一个例子:

    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[];
    }
    

    装饰器@Tree() 用于告诉TypeORM 每个实例都有自己的自引用。每个项目都应该有一个父母,并且应该有几个孩子。可以分别使用装饰器@TreeParent()@TreeChildren() 设置祖先和后代。查看documentation 了解有关@Tree() 装饰器可用的不同模式的更多详细信息。

    【讨论】:

      【解决方案2】:

      由于您已经加载了eager,每个Category 对象都在尝试加载其所有符合categoryList 条件的子对象。由于categoryList 也是Category 实体的列表,它的所有子项也都在尝试加载他们自己的categoryList。这种情况一直持续到堆栈溢出为止。

      Category实体中移除eager加载:

      @Entity('categoryenter code here')
      export class Category{
        @PrimaryGeneratedColumn({ type: 'int' })
        id: Category;
      
        @OneToMany(() => Category, category => category.category)
        categoryList: Category[];
      
        @ManyToOne(() => Category, (category) => category.categoryList)
        category: Category;
      }
      

      【讨论】:

        猜你喜欢
        • 2015-03-13
        • 1970-01-01
        • 1970-01-01
        • 2016-08-14
        • 2019-06-04
        • 1970-01-01
        • 1970-01-01
        • 2014-10-02
        • 2021-02-20
        相关资源
        最近更新 更多