sql - 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的关系提供两列。
如果你们中的任何人都可以帮助我,那就太好了。也许有必要向您提供有关其他实体的更多信息?
亲切的问候,
数字黑客
解决方案
每个关系都应该在自己的表中。如果您在一张表中表示两个关系,您将创建重复并最终可能导致不一致。
例子
假设您有一个食谱 MyRecipe,其中一个步骤 Step1 包含两种成分。现在您想将 Step1 移动到另一个配方 OtherRecipe。因为关系MyRecipe <-> Step1
被表示两次(重复),所以您必须更改多个条目。如果你忘记了一个,你最终会得到损坏的数据。
ingredient_steps_step:
MyRecipe <-> Step1 <-> IngredientA
MyRecipe <-> Step1 <-> IngredientB
我将按如下方式对数据进行建模:
steps:
Step1 -> MyRecipe
step_ingredients:
Step1 <-> IngredientA
Step1 <-> IngredientB
这样,您就没有重复。我假设食谱的成分是其所有步骤的成分的结合。
推荐阅读
- android - Android WebView 滚动不流畅并跳转/有回调
- html - div 内的图像根据 Edge 上的标题长度调整大小
- angular - matTable:更改数据源行后 UI 未更新
- c++ - 在 Qt3D 中禁用抗锯齿
- amazon-web-services - 浏览器中 S3 存储桶对象上的 403
- ssl - Plesk > 11 中域的 SSL 证书默认值
- javascript - 离子页面数据不更新
- google-apps-script - 为什么 ClockTriggerBuilder 的 after() 方法运行不正确?
- javascript - ReactJs 中如何提供存储增强器的输入
- c# - AutoMapper 9.x 如何更新现有实体对象