首页 > 解决方案 > 需要将 psql 查询转换为 typeorm

问题描述

我需要每天/每周/每月获取数据。所以我使用 date_trunc() 函数来获取这种类型的记录。我进行了 psql 查询,但我需要将其转换为 typeorm 代码,因为我是 typeorm 堆栈的新手。下面是查询

select date_trunc('day', e."createdAt") as production_to_month, count(id) as count from events e 
where e."createdAt" between '2021-05-10' and '2021-05-17' and e."type" = 'LOGIN'
group by date_trunc('day', e."createdAt") 
order by date_trunc('day', e."createdAt") asc

需要转换这个

标签: node.jsdatabasetypescriptpostgresqltypeorm

解决方案


您需要使用查询生成器来获得所需的结果。

查询将是 -

  return await getRepository(Events)
  .createQueryBuilder("e")
  .select("date_trunc('day',`e`.`createdAt`)","production_to_month")
  .addSelect("count(`id`)","count")
  .where("`e`.`createdAt` between '2021-05-10' and '2021-05-17'")
  .andWhere("`e`.`type` = 'LOGIN'")
  .groupBy("date_trunc('day',`e`.`createdAt`)").
  .orderBy("date_trunc('day',`e`.`createdAt`)","ASC")
  .printSql()
  .getRawMany()

推荐阅读