TypeORM实体继承ManyToOne关系

时间:2019-02-28 19:06:11

标签: node.js typeorm

我在Node.JS中使用TypeORM,并且想使用实体继承来实现BaseRecord:

export abstract class BaseRecord {
  @CreateDateColumn({type: 'timestamp'})
  public created_at: Date;

  @UpdateDateColumn({type: 'timestamp'})
  public updated_at: Date;

  @ManyToOne(type => User, user => user.records_created)
  public created_by: User

  @ManyToOne(type => User, user => user.records_updated)
  public updated_by: User
}

我想扩展其他实体。删除@ManyToOne关系时,此操作按预期工作:

@Entity()
export class Address extends BaseRecord {
  @PrimaryGeneratedColumn()
  public id: number;

  @Column({ nullable: true, type: "text" })
  public alias: string;

  @Column({ type: "text" })
  public street_1: string;

  @Column({ nullable: true, type: "text" })
  public street_2: string;

  @Column({ type: "text" })
  public city: string;

  @Column({ type: "text" })
  public state: string;

  @Column({ type: "text" })
  public zip_code: string;

  @Column(type => GeoLocation)
  public geo_location: GeoLocation
}

有人遇到这种继承实体的方法或方法并具有ManyToOne关系吗?

1 个答案:

答案 0 :(得分:1)

我建议通过Embedded Entity

对继承使用合成

嵌入式列是接受具有自己列的类并将这些列合并到当前实体的数据库表中的列。

您可以根据需要在嵌入式类中使用任意多的列(或关系)。您甚至可以在嵌入式类中嵌套嵌套的列。

import {Column} from "typeorm";

export class Assigned {
    @ManyToOne(type => User, user => user.records_created)
    public created_by: User

    @ManyToOne(type => User, user => user.records_updated)
    public updated_by: User
}

export class Dated {
    @CreateDateColumn({type: 'timestamp'})
    public created_at: Date;

    @UpdateDateColumn({type: 'timestamp'})
    public updated_at: Date;
}

然后使用它

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
import {Assigned} from "./Assigned";
import {Dated} from "./Dated";

@Entity()
export class Address extends BaseRecord {
  // ...Other columns

  @Column(type => Assigned)
  assigned: Assigned;

  @Column(type => Dated)
  dated: Dated;
}

您可以根据需要在嵌入式类中使用任意多的列(或关系)。 您甚至可以在嵌入式类中嵌套嵌套的列。