postgresql 原始SQL正常工作时TypeORM查询生成器返回空数组

qhhrdooz  于 2022-11-04  发布在  PostgreSQL
关注(0)|答案(2)|浏览(203)

我正在尝试使用createQueryBuilder运行以下类型的查询。我已经验证了所有实体都已正确创建和联接。但是,运行以下查询将返回一个空数组:

let apiKey = await getConnection()
    .createQueryBuilder()
    .from(ApiKey, "apiKey")
    .innerJoinAndSelect("apiKey.site", "site")
    .where("site.domain = :domain", { domain: "mysitename.com" })
    .andWhere("apiKey.key = :key", { key })
    .getMany()

但是!当我用getSql()替换getMany()时,复制原始SQL并运行它,它工作了!我得到了我所期望的结果:

SELECT "site"."id" AS "site_id", "site"."domain" AS "site_domain", "site"."name" AS "site_name", "site"."createdAt" AS "site_createdAt", "site"."apiKeyId" AS "site_apiKeyId", "site"."userId" AS "site_userId" FROM "api_key" "apiKey" INNER JOIN "site" "site" ON "site"."id"="apiKey"."siteId" WHERE "site"."domain" = 'mysitename.com'

我尝试构建这个查询的方式是否有什么明显的错误?
提前感谢您的帮助!

4zcjmb1e

4zcjmb1e1#

.getMany()返回Entity[]的Promise类型,根据查询的性质,我怀疑您根本没有返回实体。请尝试.getRawMany()或.getRawAndEntities()
有关详细信息,请参阅此处的QueryBuilder文档。

h6my8fg2

h6my8fg22#

您需要选择存储库

let apiKey = await getConnection()
    .getRepository(ApiKey) // <-----------
    .createQueryBuilder('apiKey') // <-----------
    .innerJoinAndSelect("apiKey.site", "site")
    .where("site.domain = :domain", { domain: "mysitename.com" })
    .andWhere("apiKey.key = :key", { key })
    .getMany()

相关问题