【问题标题】:How can we use @Tree('closure-table') in NestJs?我们如何在 NestJs 中使用 @Tree('closure-table') ?
【发布时间】:2021-10-19 12:19:09
【问题描述】:

我想使用@Tree('closure-table'),所以我有以下方法和实体:

 public async create(createCategoryDto: CreateCategoryDto) {
    try {
      const manager = getManager();
      const category = await this.categoryRepository.create(createCategoryDto);
      return await manager.save(category);
    } catch (e) {
      throw e;
    }
  }

和实体:

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

@Entity()
@Tree('closure-table')
export class Category {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @TreeChildren()
  children: Category[];

  @TreeParent()
  parent: Category;
}

但是这个不能创建树,有没有人知道这个问题?

注意: typeorm 文档的例子很简单。

【问题讨论】:

    标签: javascript mysql typescript nestjs typeorm


    【解决方案1】:

    这个对我有用:

    public async create(createCategoryDto: CreateCategoryDto) {
        try {
          if (!createCategoryDto.parentId) {
            const category = await this.categoryRepository.create(
              createCategoryDto,
            );
            return await this.categoryRepository.save(category);
          }
    
          const parent = await this.categoryRepository.findOne(
            createCategoryDto.parentId,
          );
          const child = await this.categoryRepository.create(createCategoryDto);
          child.parent = parent;
          return await this.categoryRepository.save(child);
        } catch (e) {
          throw e;
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2021-03-10
      • 2023-02-02
      • 2019-07-05
      • 2021-07-01
      • 1970-01-01
      • 2019-05-01
      • 2022-11-15
      • 2019-12-15
      相关资源
      最近更新 更多