[英]Add a field in a many-to-one relation in NestJS
我正在嘗試開發一個小應用程序來記錄烹飪食譜。 為此,我用 nestJS 聲明了 2 個實體,允許我管理食譜和另一個來管理成分。 我還創建了第三個實體來記錄所需成分的數量:
// 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();
但是這個方法只返回我的食譜 object 沒有成分......
[
{
"id": 1,
"createdAt": "2020-04-30T09:12:22.000Z",
"updatedAt": "2020-04-30T09:12:22.000Z",
"title": "Test",
"image": null
}
]
從那里,我迷路了......我怎樣才能直接從我的服務中獲取我的成分列表(至少是名稱和數量字段)?
預先感謝您的幫助。
使用leftJoin
可以讓您在沒有選擇的情況下加入數據。 如果它有成分,它會選擇配方,但不會返回它的成分。 如 TypeORM 文檔中所述:
您可以在不選擇數據的情況下加入數據。 為此,請使用
leftJoin
或innerJoin
: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'
如果他有照片,這將是 select Timber,但不會返回他的照片。
對 select 的成分嘗試使用leftJoinAndSelect
代替。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.