Search code examples
sqlnode.jstypescripttypeorm

TypeORM, How to create PrimaryGeneratedColumn with a prefix


I'm using TypeORM and want to create PrimaryGeneratedColumn as zerofill value with a prefix, like PR000001, PR000002 and so on. How can I get that? Now I found EntityListeners, so I can create a regular PrimaryGeneratedColumn and just add zerofill value with a prefix onInstert, onUpdate and so on, but it doesn't look like a good solution.


Solution

  • if anybody curious about, I found a hacky-solution

    @EventSubscriber()
    export class MyEntitySubscriber implements EntitySubscriberInterface {
    
        public afterInsert(event: InsertEvent<any>) {
            const repo = event.manager.connection.getRepository(MyEntity);
            event.entity.prefixedId = `PR${zerofill(6, event.entity.id)}`;
            repo.save(event.entity);
        }
    
    }
    

    also, related ticket https://github.com/typeorm/typeorm/issues/1571