MikroOrm自我父母关系

问题描述

你好,我有以下关系:

enter image description here

我尝试在我的实体中执行此操作以代表父母的关系:

@Entity({ tableName: 'product_instances' })
export class ProductInstance {
  @PrimaryKey()
  public readonly serial_number: string;
  @property()
  public patrimony_code?: string;
  @Enum()
  public type: ProductTypes;
  @ManyToOne(() => Product,{ fieldName: 'product_id' })
  public product: Product;
  @ManyToOne(() => Contract,{ fieldName: 'contract_id' })
  public contract: Contract;
  @ManyToOne(() => Employee,{ fieldName: 'employee_id' })
  public employee: Employee;
  @OnetoMany({
    entity: () => ProductInstance,mappedBy: 'parent',orphanRemoval: true,})
  public parent = new Collection<ProductInstance>(this);
  @property()
  public created_at = new Date();
  @Property({ onUpdate: () => new Date() })
  public updated_at = new Date();
  @property()
  public deleted_at?: Date;

  constructor(container: instanceContainer) {
    this.serial_number = container.serial_number;
    this.patrimony_code = container.patrimony_code;
    this.type = ProductTypes[container.type];
    this.employee = container.employee;
    this.contract = container.contract;
    this.product = container.product;
  }

  static build = (container: instanceContainer): ProductInstance => {
    return new ProductInstance(container);
  };
}

但是由于某种原因,我在一对多关系中遇到以下错误

ProductInstance.parent和ProductInstance.parent都定义为 拥有的一面,在其中一面使用'mappedBy'

我应该建立一对多关系和一对多关系吗?

解决方法

您为父级关系添加了OneToMany关系。 就是说,您定义了parent父母名单。

此外,您将parent定义为反向关系键。

您应该更改此设置:

  @OneToMany({
    entity: () => ProductInstance,mappedBy: 'parent',orphanRemoval: true,})
  public parent = new Collection<ProductInstance>(this);

对此:

  @ManyToOne({
    entity: () => ProductInstance,mappedBy: 'children',})
  public parent: ProductInstance;

  @OneToMany({
    entity: () => ProductInstance,})
  public children = new Collection<ProductInstance>(this);