【问题标题】:TypeORM multiple on conditions for join clause用于连接子句的 TypeORM 多重条件
【发布时间】:2021-02-20 04:14:57
【问题描述】:

我正在开发一个使用 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();

但这不会返回相同的结果。有没有办法以编程方式构建此查询,还是我被查询字符串卡住了?

【问题讨论】:

    标签: sql node.js typescript postgresql typeorm


    【解决方案1】:

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      • 2022-09-25
      • 2020-06-12
      • 2011-12-11
      • 1970-01-01
      相关资源
      最近更新 更多