Typeorm 如何在 findOne() 中使用关系
Typeorm how to use relations in findOne()
我是第一次使用 TypeORM,但我在尝试使用 FK 从另一个 table 获取条目时遇到了困难。但是我得到了这个错误。
Error: Relation "ingredientCategoryId" was not found; please check if
it is correct and really exists in your entity.
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);
}
试试这个:
relations: ['ingredientsCategory'],
而不是:
relations: ['ingredientCategoryId'],
我是第一次使用 TypeORM,但我在尝试使用 FK 从另一个 table 获取条目时遇到了困难。但是我得到了这个错误。
Error: Relation "ingredientCategoryId" was not found; please check if it is correct and really exists in your entity.
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);
}
试试这个:
relations: ['ingredientsCategory'],
而不是:
relations: ['ingredientCategoryId'],