question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to inherit multiple columns/classes?

See original GitHub issue

Issue 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:closed
  • Created 4 years ago
  • Reactions:3
  • Comments:24 (5 by maintainers)

github_iconTop GitHub Comments

24reactions
abinicicommented, Jul 19, 2022

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

export type Constructor<T = {}> = new (...args: any[]) => T;

export function EntityWithBase() {
    abstract class AbstractBase extends Base {
        @PrimaryGeneratedColumn()
        id: number;
    }
    return AbstractBase;
}

export function EntityWithTenant<TBase extends Constructor>(Base: TBase) {
    abstract class AbstractBase extends Base {
        @Column({ nullable: false })
        tenantId: number;
    }
    return AbstractBase;
}

export function EntityWithDates<TBase extends Constructor>(Base: TBase) {
    abstract class AbstractBase extends Base {
        @Column({
            type: 'timestamp without time zone',
            nullable: true
        })
        public updatedAt: number;

        @Column({
            type: 'timestamp without time zone',
            nullable: true
        })
        public createdAt: number;

        @BeforeUpdate()
        public setUpdatedAt() {
            this.updatedAt = Math.floor(Date.now() / 1000);
        }

        @BeforeInsert()
        public updateDates() {
            const time = Math.floor(Date.now() / 1000);
            this.createdAt = time;
            this.updatedAt = time;
        }
    }
    return AbstractBase;
}

And here is how to use these mixins with an entity:

@Entity('Users')
export class UserEntity extends EntityWithDates(EntityWithTenant(EntityWithBase())) {

    @Column({
        name: 'EmailAddress',
        length: 256
    })
    email: string;

}

By using these functions, we end up building this chain of subclassing:

UserEntity > EntityWithBase > EntityWithTenant > EntityWithDates

When I run the application, TypeORM is able to sync this entity correctly with the database:

CREATE TABLE "public"."Users" (
    "Id" int4 NOT NULL DEFAULT nextval('"Users_Id_seq"'::regclass),
    "TenantId" int4 NOT NULL,
    "UpdatedAt" timestamp,
    "CreatedAt" timestamp,
    "EmailAddress" varchar(256) NOT NULL,
    PRIMARY KEY ("Id")
);
1reaction
ghostcommented, Jul 19, 2022

Hats off man, hats off!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Multiple Inheritance Columns in Rails? - Stack Overflow
I have an active record class (Animal) that has a type column and a gender column. Theoretically, I'd like to create multiple classes...
Read more >
Multiple Inheritance in Python - GeeksforGeeks
When a class is derived from more than one base class it is called multiple Inheritance. The derived class inherits all the features...
Read more >
Mapping Class Inheritance Hierarchies
Querying for a particular subclass in the hierarchy will render as a SELECT against the base table, which will include a WHERE clause...
Read more >
When To Use Single Table Inheritance vs Multiple ... - Steven Li
Rails supports STI right out of the box simply by inheriting subclasses from an ActiveRecord parent class which has a type column in...
Read more >
Inheritance - Propel ORM
A table using Single Table Inheritance requires a column to identify which class should be used to represent the table row. Classically, this...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found