0

你好我有以下关系:

在此处输入图像描述

我试图在我的实体中这样做以表示父母的关系:

@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”

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

4

1 回答 1

1

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,
    mappedBy: 'parent',
  })
  public children = new Collection<ProductInstance>(this);

于 2020-11-12T06:33:51.433 回答