如何在 typeorm 中合并两个表?

Vla*_*lub 4 typeorm nestjs

我想在 typeorm 中合并两个表。

第一个版本:我为每个表创建了 sql 原始查询

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

    const tableTg = this.tags.createQueryBuilder('tg')
        .select(['id', 'name'])
        .getQuery();
Run Code Online (Sandbox Code Playgroud)

使用 union 创建 slq 原始查询后:

const tags = await entityManager.query(`${ tableUn } UNION ${ tableTg }`);
Run Code Online (Sandbox Code Playgroud)

创建新实体并向其插入接收到的数据。

const createdEntity = entityManager.create(TableUnion, tags);
Run Code Online (Sandbox Code Playgroud)

最后,我想在连接查询生成器中使用这个实体,但它不起作用

      const result = await connection.createQueryBuilder()
          .from(createdEntity, 'cE')
          .getRawMany();
Run Code Online (Sandbox Code Playgroud)

第二个版本:

    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'
        )
Run Code Online (Sandbox Code Playgroud)

它创建了包含两个表中的数据和列的表,但未连接

Ima*_*our 5

我为自己找到了这个解决方案。

// two queries with different parameters from the same table
const query1WithParams = repo.createQueryBuilder("table1")
.select("table1.id")
.where("table1.id = :input_id" , { input_id : 5 })
.getQueryAndParameters();

const query2WithParams = repo.createQueryBuilder("table1")
.select("table1.id")
.where("table1.id = :input_id" , { input_id : 10 })
.getQueryAndParameters();
Run Code Online (Sandbox Code Playgroud)

请记住,如果您没有任何参数,最好使用.getQuery()而不是.getQueryAndParameters(). 那么让我解释一下您可能会遇到的问题。如果您没有参数,一切都很好,您无需任何准备即可使用查询。但是如果您有像我在顶部的示例一样的参数,您必须自己更改参数占位符以避免它们发生冲突。

如果您查看这两个查询的结果,您会发现它们都有精确的WHERE子句

-- Result of query1WithParams and the parameter must be 5
WHERE "table1"."id" > $1

-- Result of query2WithParams and the parameter must be 10
WHERE "table1"."id" > $1 
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我们有一个占位符代表两个值(5,),但它不起作用,因此我们必须将其中之一更改为$2 (不同的数据库有自己的参数格式,此示例是关于Postgres. 如果您想了解更多信息)看看这个问题。)您可以像这样更改其中一个:

-- Result of query1WithParams and the parameter must be 5
WHERE "table1"."id" > $1

-- Result of query2WithParams and the parameter must be 10
WHERE "table1"."id" > $1 
Run Code Online (Sandbox Code Playgroud)

之后,您必须将参数数组合并为一个(它们的顺序很重要)

const [query2, params2] = query2WithParams
const correct_query2 = query.replace("$1", "$2")
Run Code Online (Sandbox Code Playgroud)

现在您可以使用它们作为联合的输入查询。

const [query1, params1] = query1WithParams
const correct_params = [...params1, ...params2]
Run Code Online (Sandbox Code Playgroud)