使用TypeORM在同一个表中进行一对一关系

问题描述 投票:0回答:1

为了更好的结构,我想在两个实体中拆分一个更复杂的表,从而产生两个类。通过指定一对一关系,我希望从一个ORM中,两者都在同一个表中提供 - 原因连接在1:1关系中没有意义,只影响性能。

所以我有以下实体:

@Entity()
export class A {
    @PrimaryColumn() id: number
    // Other Properties
    @OneToOne(type => B)
    b: B
}
@Entity()
export class B {
    @Colum()
    someOtherProperty: number
}

但这不起作用,我得到一个错误,B没有主键。如果我指定一个主键(没有意义),我有两个表ABThe documentation只描述了与两张桌子的1:1关系。

为什么他们在这里建立一个不必要的第二张桌我使用了其他强大的ORM,比如EntityFramework,这是1:1关系的默认行为。只在需要时才生成附加表(1:n,n:n关系)。

mysql node.js typescript database-relations typeorm
1个回答
0
投票

在TypeOrm中,One-To-One关系仅在2个表之间起作用。在该示例中,您需要使用“嵌入实体”模式。

它必须看起来像:

@Entity()
export class A {
    @PrimaryColumn() id: number

    @Colum(type => B)
    b: B
}

@Entity()
export class B {
    @Colum()
    someOtherProperty: number
}

这里是文档和示例:http://typeorm.io/#/embedded-entities

© www.soinside.com 2019 - 2024. All rights reserved.