Search code examples
node.jsnestjstypeorm

Nestjs, How to get entity table name?


How to get entity table name ? (ex: member-pre-sale-detail) I want to set table comment

// Seeder: Clear & set Comment
export default class ClearAllSeed implements Seeder {
    public async run(factory: Factory, connection: Connection): Promise<void> {


        const deleteEntities = [
            {table: OrderHead, comment: '訂單/主表'},
       ]

       for(const entity of deleteEntities){
            await connection
                .createQueryBuilder()
                .delete()
                .from(entity.table)
                .execute();

            await connection
                // >>>> but table name is MemberPreSaleDetail not member-pre-sale-detail
                .query(`alter table ${entity.table.name} comment '${entity.comment}'`);
        }
   }
}

// Sampel Entity
@Entity('member-pre-sale-detail')
export class MemberPreSaleDetail {
  @PrimaryGeneratedColumn({unsigned: true})
  id?: number;

  @Column({comment: '幾批(整批)', type: 'mediumint', default: 0})
  batchQty: number;
}

Expected behavior

get the 'member-pre-sale-detail' string

Environment

Nest version: 7.0.7 For Tooling issues: - Node version: v14.5.0 - Platform: Mac

Solution

  • I am guessing you are using TypeORM. In that case:

    You could get the entity metadata by calling connection.getMetadata(MemberPreSaleDetail).

    This method returns an EntityMetadata, which has name, tableName and givenTableName properties. For your usecase I guess you could simply use givenTableName.