如何在TypeORM中使用SUM()和getMany()?

问题描述 投票:0回答:3

我正在尝试使用 TypeOrm/PostgreSQL 编写一个查询组(“pg”:“^8.3.3”,“typeorm”:“^0.2.25”)。

我需要运行的 SQL 查询是:

SELECT
    ad_id,
    COUNT (impression_id) AS impressions
FROM
    Ad_impressions
GROUP BY
    ad_id
ORDER BY
    impressions

我已阅读所有文档并在网上进行了大量搜索,但无法使其正常工作。这是我最好的尝试:

await getConnection()
  .getRepository(Ad_impressions)
  .createQueryBuilder('Ad_impressions')
  .select([
    'Ad_impressions.ad_id',
    'COUNT(Ad_impressions.impression_id) as count',
  ])
  .groupBy("Ad_impressions.ad_id")
  .orderBy('impressions', 'DESC')
  .getMany();
postgresql typeorm
3个回答
0
投票

使用 getRawMany 而不是 getMany。

await getConnection().getRepository(Ad_impressions).createQueryBuilder('Ad_impressions').select([
'Ad_impressions.ad_id',
'COUNT(Ad_impressions.impression_id) as count',]).groupBy("Ad_impressions.ad_id").orderBy('impressions', 'DESC').getRawMany();

0
投票

当我尝试获取

SUM
时,我遇到了同样的问题。

const photosSums = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("user.id")
.addSelect("SUM(user.photosCount)", "sum")
.groupBy("user.id")
.getRawMany()

// result will be like this: [{ id: 1, sum: 25 }, { id: 2, sum: 13 }, ...]

getRawMany()
getRawOne()
解决了我的问题。

此处描述的TypeOrm


0
投票

如果您想将 SUM() 函数与 .getMany() 结合使用,您可以通过添加一个附加列来表示选项 {select: false} 的计数来修改您的 Ad_impressions 实体,这样该列用于计算目的,但在常规查询中默认不选择。 以下是实现此方法的方法

@Column({ select: false, nullable: true })
  count: string;

然后在查询生成器中

await getConnection()
  .getRepository(Ad_impressions)
  .createQueryBuilder('ad_impressions')
  .select([
    'ad_impressions.ad_id',
    'COUNT(ad_impressions.impression_id) as ad_impressions_count',
  ])
  .groupBy('ad_impressions.ad_id')
  .orderBy('impressions', 'DESC')
  .getMany();
© www.soinside.com 2019 - 2024. All rights reserved.