【问题标题】:TypeORM: duplicate key while saving relationships with existing entitiesTypeORM:重复键,同时保存与现有实体的关系
【发布时间】:2020-09-12 01:30:51
【问题描述】:

我在 TypeORM 中有以下实体:

@Entity('category')
export class Category {

  @Column({ length: 80 })
  public name: string;

  @OneToOne(
    (): ObjectType<Category> => Category,
    (category: Category): Category => category.parent,
    {
      cascade: ['insert', 'update'],
    }
  )
  @JoinColumn({ name: 'parent', referencedColumnName: 'id' })
  public parent: Category;
}

接下来,我在我的数据库中保存一些类别:

let parentCategory = new Category();
parentCategory.name = 'Parent Category';

let childCategory = new Category();
childCategory.name = 'Child Category';
childCategory.parent = parentCategory;

connection.manager.save(childCategory);

最后,我想添加一个新的“父类别”子类别(考虑到父类别是从数据库中加载并包含其 ID):

let newChildCategory = new Category();
newChildCategory.name = 'New Child Category';
newChildCategory.parent = childCategory.parent; //<- childCategory.parent contains the parent ID

connection.manager.save(newChildCategory); //<- Throws duplicate key error due to cascade

一个可行的解决方案是定义ON DUPLICATE KEY 行为,它必须根据this information 手动实现。是否有另一种解决方案可以在保存实体的同时不必像我的示例中那样编写整个查询?

This GitHub repository 包含复制问题的应用程序。

【问题讨论】:

    标签: node.js typescript typeorm


    【解决方案1】:

    你可以试试

    @ManyToOne(
        type => Category,
        category => category.children,
        {
          cascade: ['insert', 'update'],
        }
    )
    public parent: Category;
    
    @OneToMany(
        type => Category,
        category => category.parent,
        {
          cascade: ['insert', 'update'],
        }
    )
    public children: Category[];
    

    我不确定这是您问题的根本原因,但parent 的类型应该是Category 而不是category。奇怪的是你的 IDE 没有警告你。

    但请注意,因为您将类别-父关系定义为 OneToOne 类型,但从您提供的示例中,您将其用作 OneToMany/ManyToOne 关系!

    【讨论】:

    • 该解决方案尚未解决我的问题。 “类别”是我忘记在这里修正的错字。我会在我的问题中解决它。我试图通过仅指向父母来避免“许多”部分。我创建了一个 GitHub 存储库来复制该问题。我将其粘贴在我的问题中以便于调查。
    • 通过说category =&gt; category.parent,您是说关系的反面是在相关实例的parent 属性上建立的,但事实并非如此,因为如果y 是@987654332 @ 的父级,x 不能清楚地同时是 y 的父级。无论如何,我看不到“避免'许多'部分”背后的逻辑。通过像您一样定义关系,一个类别可以有一个父类别,并且只能是一个类别的父类别?您确定吗?在我的主要答案中,我完全忽略了这一点,我的错。您应该为反面定义另一个字段。
    • 我想我明白你的意思了。但是,即使我使用 OneToMany,我仍然对重复键有同样的问题。我向我的 GitHub 存储库发送了强制更新。如果你有时间,我创建了这个聊天室来讨论:chat.stackoverflow.com/rooms/214610/typeorm
    • 我更新了我的原始答案,以更好地反映您应该尝试的更改。顺便说一句,我进了房间。
    • 你发现这个问题了吗? @saulotoledo 吗?不使用 ON DUPLICATE KEY ?
    猜你喜欢
    • 1970-01-01
    • 2019-04-24
    • 2012-01-14
    • 2012-07-28
    • 2021-12-27
    • 2020-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多