在NestJS中的多对一关系中添加一个字段



我正在尝试开发一个小型应用程序来记录烹饪食谱。为了做到这一点,我用nestJS声明了两个实体,允许我管理食谱,另一个实体管理配料。我还创建了第三个实体来记录所需成分的数量:

数据库图

// recipe.entity.js
@Entity()
export class Recipe {
@PrimaryGeneratedColumn()
id: number
@Column('datetime')
createdAt: Date
@Column('datetime')
updatedAt: Date
@Column('varchar', { length: 100 })
title: string;
@Column('varchar', {nullable: true})
image: string;
@OneToMany(type => RecipeIngredients, recipeIngredients => recipeIngredients.recipe)
ingredients: RecipeIngredients[];
}
// ingredient.entity.js
@Entity()
export class Ingredient {
@PrimaryGeneratedColumn()
id: number
@Column('datetime')
createdAt: Date
@Column('datetime')
updatedAt: Date
@Column('varchar', { length: 100 })
name: string;
@Column('varchar', {nullable: true})
image: string;
@OneToMany(type => RecipeIngredients, recipeIngredients => recipeIngredients.ingredient)
recipes: RecipeIngredients[];
}
// recipe_ingredients.entity.js
@Entity()
export class RecipeIngredients {
@PrimaryGeneratedColumn()
id: number
@ManyToOne(type => Recipe, recipe => recipe.ingredients)
recipe: Recipe
@ManyToOne(type => Ingredient)
ingredient: Ingredient
@Column()
quantity: string;
}

首先,我希望能够检索到一个包含必要成分列表的食谱:

const recipe = await this.recipesRepository.createQueryBuilder('recipe')
.where('recipe.id = :recipeId', {recipeId: _id})
.leftJoin('recipe.ingredients', 'recipe_ingredients')
.leftJoin('recipe_ingredients.ingredient', 'ingredient')
.getMany();

但是这个方法只返回我的配方对象,而不返回配料。。。

[
{
"id": 1,
"createdAt": "2020-04-30T09:12:22.000Z",
"updatedAt": "2020-04-30T09:12:22.000Z",
"title": "Test",
"image": null
}
]

从那里,我迷失了。。。如何直接从我的服务中获得配料列表(至少是名称和数量字段(?

提前感谢您的帮助。

使用leftJoin可以在不选择数据的情况下连接数据。如果有配料,它会选择配方,但不会返回配料。如TypeORM文档所示:

您可以在不选择数据的情况下加入数据。要执行此操作,请使用leftJoininnerJoin:

const user = await createQueryBuilder("user")
.innerJoin("user.photos", "photo")
.where("user.name = :name", { name: "Timber" })
.getOne();

这将生成:

SELECT user.* FROM users user
INNER JOIN photos photo ON photo.user = user.id
WHERE user.name = 'Timber'

如果Timber有照片,这将选择他,但不会返回他的照片。

要选择成分,请尝试使用leftJoinAndSelect

最新更新