How to inherit multiple columns/classes?
See original GitHub issueIssue type:
[X] question [ ] bug report [ ] feature request [ ] documentation issue
Database system/driver:
[ ] cordova
[ ] mongodb
[ ] mssql
[X] mysql
/ mariadb
[ ] oracle
[ ] postgres
[ ] cockroachdb
[ ] sqlite
[ ] sqljs
[ ] react-native
[ ] expo
TypeORM version:
[X ] latest
[ ] @next
[ ] 0.x.x
(or put your version here)
I have a slug column and timestamps columns I want to be able to re-use across other models inside my application.
How can I “extend” both of these classes into my main entity? I’ve read there’s Mixins but not sure if it will work with TypeORM? Is there any examples or anyone have any suggestions?
// timestamps.ts export class Timesamps { // … @CreateDateColumn() created_at: string;
@UpdateDateColumn()
updated_at: string;
}
// slug.ts export Class Slug { … @Column({type: “varchar”, unique: true, length: 255, nullable: false}) @Length(5, 25) @IsSlug({ message: “Text must be a valid slug.” }) slug: string; }
// Status.ts @Entity() class Status … (should have access to all the methods from the two classes above)
How can Status inherit both the slug and timestamp classes?
Thanks
Issue Analytics
- State:
- Created 4 years ago
- Reactions:3
- Comments:24 (5 by maintainers)
Top GitHub Comments
@alexeightsix, I have an example which I think solves your issue.
To inherit columns in TypeORM you need to write an abstract class which your entity will inherit from. So I wrote a function that returns an abstract class through a class expression:
And here is how to use these mixins with an entity:
By using these functions, we end up building this chain of subclassing:
When I run the application, TypeORM is able to sync this entity correctly with the database:
Hats off man, hats off!