你好,我有以下关系:
我尝试在我的实体中执行此操作以代表父母的关系:
@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'
我应该建立一对多关系和一对多关系吗?
答案 0 :(得分: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);