【问题标题】:TypeORM: @JoinTable with three columnsTypeORM:@JoinTable 三列
【发布时间】:2019-07-20 05:28:16
【问题描述】:

我有一个关于 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

所以,这是我的食谱的三个主要实体。一个食谱可以有多个步骤(ma​​ny-steps-to-one-recipe),一个食谱可以有多种成分(ma​​ny-ingredients-到-一个-食谱)

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

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;  

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

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

亲切的问候,

数字黑客

【问题讨论】:

  • 您得到想要的答案了吗?可以发在这里吗...

标签: sql typescript composite-primary-key nestjs typeorm


【解决方案1】:

每个关系都应该在自己的表中。如果您在一张表中表示两个关系,则会产生重复并最终导致不一致。

示例

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

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

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

steps:
Step1 -> MyRecipe

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

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

【讨论】:

    猜你喜欢
    • 2019-12-15
    • 2013-01-31
    • 2021-04-26
    • 2022-07-07
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多