简体   繁体   中英

TypeORM Entity Inheritance ManyToOne Relationship

I'm using TypeORM in Node.JS and would like to use the entity inheritance to implement a 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
}

Which I would like to extend other entities by. This works as expected when removing the @ManyToOne relationship:

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

Has anyone run into this or a method to inherit entity and have ManyToOne relationships?

I suggest using composition over inheritance with an Embedded Entity

An embedded column is a column which accepts a class with its own columns and merges those columns into the current entity's database table.

You can use as many columns (or relations) in embedded classes as you need. You even can have nested embedded columns inside embedded classes.

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;
}

then use it

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;
}

You can use as many columns (or relations) in embedded classes as you need. You even can have nested embedded columns inside embedded classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM