【问题标题】:Typeorm how to use relations in findOne()Typeorm 如何在 findOne() 中使用关系
【发布时间】:2021-06-11 13:09:12
【问题描述】:

我第一次使用 TypeORM,但在尝试使用 FK 从另一个表中获取条目时遇到了困难。但是我得到了这个错误。

错误:未找到关系“ingredientCategoryId”;请检查是否 它是正确的,并且确实存在于您的实体中。

ingredient.entity

@Entity('ingredient')
export class IngredientEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ nullable: false })
  ingredientCategoryId: number;

  @ManyToOne(
    () => IngredientsCategoryEntity,
    (ingredientsCategory) => ingredientsCategory.ingredient,
    { eager: true },
  )
  @JoinColumn({ name: 'ingredientCategoryId', referencedColumnName: 'id' })
  ingredientsCategory: IngredientsCategoryEntity;
}

ingredientsCategory.entity

@Entity('ingredientsCategory')
export class IngredientsCategoryEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @OneToMany(
    () => IngredientEntity,
    (ingredient) => ingredient.ingredientsCategory,
  )
  ingredient: IngredientEntity[];
}

ingredient.service

  async getIngredientCategory(id: number): Promise<any> {
    const ingredient: IngredientEntity = await this.repo.findOne({
      where: { id: id },
      relations: ['ingredientCategoryId'],
    });
    return ingredient.ingredientsCategory;
  }

ingredientsCategory.controller

  @Get('/:id/ingredientsCategoryList')
  async getCategory(@Param('id', ParseIntPipe) id: number) {
    return this.ingredientService.getIngredientCategory(id);
  }

【问题讨论】:

    标签: typescript postgresql orm nestjs typeorm


    【解决方案1】:

    试试这个:

    relations: ['ingredientsCategory'],
    

    代替:

    relations: ['ingredientCategoryId'],
    

    【讨论】:

    • 同样的错误 > 未找到关系“ingredientCategory”;请检查它是否正确并确实存在于您的实体中。
    • 嗨。你用的是单数(ingredientCategory)还是复数(ingredientsCategory)?
    猜你喜欢
    • 2022-01-02
    • 2022-01-23
    • 2021-07-06
    • 1970-01-01
    • 2021-10-27
    • 2021-02-20
    • 2021-04-04
    • 1970-01-01
    • 2022-07-05
    相关资源
    最近更新 更多