首页 > 解决方案 > TypeORM:@JoinTable 三列

问题描述

我有一个关于 typeorm 和@JoinTable - 和@RelationId -Decorator 的问题。也许任何人都可以帮助回答我的问题,给我一个提示或理想地解决我的问题。

我正在使用带有 typeorm 的 nestjs 来为我和我的家人提供一个带有食谱的私有 api。

如果我将数据库结构分解到最低限度,我们会得到三个主要实体:

recipe
- id INT(11)
- name VARCHAR(255)
# PRIMARY KEY is id

ingredient
- id INT(11) // not autoincrement, fetched from https://www.programmableweb.com/api/chomp
- name VARCHAR(255)
- recipeId INT(11)
# PRIMARY KEY is a composite key (id, recipeId) 
# FOREIGN KEY is recipeId on recipe

step
- id INT(11)
- name VARCHAR(255)
- recipeId INT(11)
# PRIMARY KEY is id
# FOREIGN KEY is recipeId on recipe

所以,这些是我的食谱的三个主要实体。一个食谱可以有多个步骤(很多步骤到一个食谱),一个食谱可以有多个成分(很多配料到一个食谱)

现在是复杂的部分。每个步骤可能与一种或多种成分有关。这导致以下关系表。

ingredient_steps_step
- ingredientId INT(11)
- stepId INT(11)
- recipeId INT(11)
# PRIMARY KEY is a composite key (ingredientId, stepId, recipeId)
# FOREIGN KEYS are ingredientId on ingredient, stepId on step, recipeId on recipe

我的成分.entity.ts 看起来像这样:

@ManyToMany(type => Step, step => step.ingredients)
@JoinTable({
  name: 'ingredient_steps_step',
  joinColumns: [
    {name: 'ingredientId'},
    {name: 'recipeId'},
  ],
  inverseJoinColumns: [
    {name: 'stepId'},
  ],
})
steps: Step[];

@RelationId((ingredient: Ingredient) => ingredient.steps)
stepIds: number[];

@PrimaryColumn()
recipeId: number;

@PrimaryColumn()
id: number;

@ManyToOne(type => Recipe, recipe => recipe.ingredients)
recipe: Recipe;  

问题是,我的成分表被填满,但关系表(成分步骤)没有被条目填满。问题是,没有像@RelationIds这样的装饰器,我可以在其中为与实体step的关系提供两列。

如果你们中的任何人都可以帮助我,那就太好了。也许有必要向您提供有关其他实体的更多信息?

亲切的问候,

数字黑客

标签: sqltypescriptcomposite-primary-keynestjstypeorm

解决方案


每个关系都应该在自己的表中。如果您在一张表中表示两个关系,您将创建重复并最终可能导致不一致。

例子

假设您有一个食谱 MyRecipe,其中一个步骤 Step1 包含两种成分。现在您想将 Step1 移动到另一个配方 OtherRecipe。因为关系MyRecipe <-> Step1被表示两次(重复),所以您必须更改多个条目。如果你忘记了一个,你最终会得到损坏的数据。

ingredient_steps_step:
MyRecipe <-> Step1 <-> IngredientA
MyRecipe <-> Step1 <-> IngredientB

我将按如下方式对数据进行建模:

steps:
Step1 -> MyRecipe

step_ingredients:
Step1 <-> IngredientA
Step1 <-> IngredientB

这样,您就没有重复。我假设食谱的成分是其所有步骤的成分的结合。


推荐阅读