在 TypeORM 中,我尝试创建一个查询生成器来生成以下 Postgres 查询:
SELECT "mt"."id" AS "id"
FROM "main_table" "mt"
WHERE "mt"."some_value" = $1
AND NOT EXISTS(SELECT 1
FROM "other_table" "ot"
WHERE "ot"."some_other_value" != $2
AND "ot"."join_id" = "mt"."join_id")
我看到自从 TypeORM 的 这个 PR 以来,我们可以在 queryBuilders 上添加 .whereExists() 。然而,我看不出有什么办法可以否定这一点。下面是 EXISTS 应该如何工作的代码片段
...
createQueryBuilder("main_table", 'mt')
.where("mt.some_value = :some_value", { some_value: 4 })
.andWhereExists(this.entityManager.createQueryBuilder()
.from(AnotherTable, 'at')
.where('ot.some_other_value != :val', {
val: 5,
})
.andWhere('mt.join_id = ot.join_id') }
但是,我不知道如何将其与 NOT (甚至 NotBrackets,因为它返回一个 whereFactory 并且无法访问这些存在方法)一起使用。
我唯一的希望是原始查询吗?
你可以做这样的事情。
我遇到了类似的问题,这对我有用。
const someValues = await dataSource
.createQueryBuilder('main_table', 'mt')
.where("mt.some_value = :some_value", { some_value: 4 })
.leftJoin('mt.other_table', 'other_table')
.andWhere((qb) => {
const query = qb
.select()
.where('other_table.some_other_value = :some_other_value', {
some_other_value : 5
})
.getQuery();
return `NOT EXISTS(${query})`;
})
.getMany();