Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 543
jmiraglia Avatar asked Feb 28 '19 19:02

jmiraglia


1 Answers

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.

like image 85
Gabriel Vasile Avatar answered Oct 14 '22 04:10

Gabriel Vasile