sql - 用于连接子句的 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();
但这不会返回相同的结果。有没有办法以编程方式构建此查询,或者我是否坚持使用查询字符串?
解决方案
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();
推荐阅读
- javascript - Shiny.onInputChange 不是函数,奇怪的错误
- arrays - 多维数组的最佳结构JSON结构是什么
- javascript - ReactJS,如何将 json 对象复制到另一个标识值更改
- c# - NSubstitute 的 Received(count) 始终为绿色(模拟具体类时)
- php - Apache 显示错误 500 而不是 php 错误
- android - 从本地资产文件夹加载 json 数据
- xamarin - Xamarin 形成圆形滑块
- javascript - 按下时禁用操作链接和按钮
- mdx - Mondrian MDX 查询错误:- 函数“{}”的所有参数必须具有相同的层次结构
- c++ - 在 C++ 中实现“Bulletproofs:机密交易等的简短证明”