How to union two tables in typeorm?

Viewed 5170

I want to union two tables in typeorm.

First version: I crated sql raw queries, for each table

    const tableUn = this.tableUnion.createQueryBuilder('tu')
        .select('id')
        .addSelect('description', 'name')
        .getQuery();

    const tableTg = this.tags.createQueryBuilder('tg')
        .select(['id', 'name'])
        .getQuery();

After create slq raw query with union:

const tags = await entityManager.query(`${ tableUn } UNION ${ tableTg }`);

Create new entity and insert received data to it.

const createdEntity = entityManager.create(TableUnion, tags);

In the end, I wanted use this entity in connection query builder, but it doesn't work

      const result = await connection.createQueryBuilder()
          .from(createdEntity, 'cE')
          .getRawMany();

Second version:

    const a = connection
        .createQueryBuilder()
        .select('*')
        .from(qb => qb
            .from(TableUnion, 'tu')
            .select('id')
            .addSelect('description', 'tu.name'),
            'ttu'
        )
        .addFrom(qb => qb
            .from(TagsEntity, 'tg')
            .select('id')
            .addSelect('tg.name'),
            'ttg'
        )

It created table with data and columns from two tables, but doesn't connect

1 Answers

I think you could do the following:

   const tableUn = this.tableUnion.createQueryBuilder('tu')
  .select('id')
  .addSelect('description', 'name')
  .getRawMany();
    
  const tableTg = this.tags.createQueryBuilder('tg')
  .select(['id', 'name'])
  .getRawMany();

   return tableUn.concat(tableTg)
Related