首页 > 解决方案 > 用于连接子句的 TypeORM 多重条件

问题描述

我正在开发一个使用 TypeORM 和 PostgreSQL 的项目,我正在尝试使用查询生成器来加入多个条件。有没有比在字符串中包含所有条件更简单/更程序化的方式来做到这一点?例如,我想构建以下查询来为用户获取朋友。在 SQL 中,此查询如下所示(注意:inRel 是传入关系的缩写,outRel 是传出关系的缩写)

-- SELECT FRIENDS FOR USER
select outRel."relatingToUserId"
from relationships outRel 
inner join relationships inRel 
    on inRel."userId" = outRel."relatingToUserId"
    and inRel."relatingToUserId" = outRel."userId"
    and inRel."type" = 'FRIEND'
    and outRel."type" = 'FRIEND'
where outRel."userId" = 'some_uuid_for_the_user';

在 TypeORM 中,我可以完成相同的结果

const relationships = await this.createQueryBuilder()
  .select('outRel.relatingToUserId')
  .from(RelationshipEntity, 'outRel')
  .innerJoin(
    RelationshipEntity,
    'inRel',
    `
      inRel.userId = outRel.relatingToUserId
      AND inRel.relatingToUserId = outRel.userId
      AND inRel.type = 'FRIEND'
      AND inRel.type = outRel.type
    `,
  )
  .where('outRel.userId = :userId', { userId })
  .getMany();

但是,我希望我应该能够做更多类似的事情

const relationships = await this.createQueryBuilder()
  .select('outRel.relatingToUserId')
  .from(RelationshipEntity, 'outRel')
  .innerJoin(RelationshipEntity, 'inRel', 'inRel.userId = outRel.relatingToUserId')
  .andWhere('inRel.relatingToUserId = outRel.userId')
  .andWhere("inRel.type = 'FRIEND'")
  .andWhere('inRel.type = outRel.type')
  .where('outRel.userId = :userId', { userId })
  .getMany();

但这不会返回相同的结果。有没有办法以编程方式构建此查询,或者我是否坚持使用查询字符串?

标签: sqlnode.jstypescriptpostgresqltypeorm

解决方案


andWhere 用在 .where 之后。尝试这个:

const relationships = await this.createQueryBuilder()
.select('outRel.relatingToUserId')
.from(RelationshipEntity, 'outRel')
.innerJoin(RelationshipEntity, 'inRel', 'inRel.userId = outRel.relatingToUserId and inRel.relatingToUserId = outRel.userId and inRel.type = outRel.type')
.where('outRel.userId = :userId', { userId })
.andWhere('inRel.type = 'FRIEND'')
.getMany();

推荐阅读