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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With