【发布时间】: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