【问题标题】:NestJS Typeorm filter relations from reponseNestJS Typeorm 从响应中过滤关系
【发布时间】:2021-03-06 18:53:48
【问题描述】:

当使用Repository.save(myEntity)时,如何确保TypeOrm只返回实体本身而不是它的关系?

给定这个示例实体

@Entity()
export class Flavor {
  @ManyToMany(
    type => Coffee,
    coffee => coffee.flavors,
  )
  coffees: Coffee[];
}
@Entity()
export class Coffee {
  @JoinTable()
  @ManyToMany(
    type => Flavor,
    flavor => flavor.coffees,
  )
  flavors: Flavor[];
}

还有这个示例服务


  async create(createCoffeeDto: CreateCoffeeDto) {
    const flavors = await Promise.all(
      createCoffeeDto.flavors.map(name => this.preloadFlavorByName(name)),
    );

    const coffee = this.coffeeRepository.create({
      ...createCoffeeDto,
      flavors,
    });
    return this.coffeeRepository.save(coffee);
  }

如何过滤响应,使其仅返回 Coffee 实体而不返回 Flavor 实体。例如这个

{
  "id": 0,
  "name": "string",
  "brand": "string",
  "recommendations": 0,
}

不是这个

{
  "id": 0,
  "name": "string",
  "brand": "string",
  "recommendations": 0,
  "flavors": [
    {
      "id": 0,
      "name": "string",
      "coffees": [
        null
      ]
    }
  ]
}

【问题讨论】:

    标签: nestjs typeorm


    【解决方案1】:

    这样做的一种方法是使用类转换器。 https://github.com/typestack/class-transformer

    首先你像这样定义你的响应类:

    export class CreateCoffeeResponseDto {
       id: number;
       name: string;
       brand: string;
       recommendations: number;
    }
    

    然后在从服务中返回时,您可以:

    return plainToClass(CoffeeCreateResponseDto, await this.coffeeRepository.save(coffee));
    

    此外,如果您将 { cascade: true } 选项对象放在您的关系上,您可以使用 .save() 调用来完成所有操作。 https://typeorm.io/#/relations/cascades

    【讨论】:

    • 级联可以隐式更新关系;使用 class-transformer gem 确实有效,但我想知道 TypeORM 本身是否有某种方法。例如,如果关联被更新,我想返回更新后的关联,但如果只有主对象被更新,我只想控制它......我基本上想要更细粒度地控制返回的关联子集,因为有时可能会有很多嵌套的关联层)
    猜你喜欢
    • 2022-01-02
    • 2021-02-20
    • 2019-12-19
    • 2021-07-21
    • 2020-10-15
    • 2020-12-03
    • 1970-01-01
    • 2018-11-22
    • 2020-09-01
    相关资源
    最近更新 更多