Pie*_*e D 1 query-builder typeorm
我有一个疑问:
topics = await topicRepository.createQueryBuilder('topic')
.leftJoinAndSelect('topic.user', 'user', 'topic.userId = user.id')
.where('topic.categoryId = :id', {
id: categoryId,
})
.andWhere('topic.title like :search', { search: `%${searchKey}%`})
// It should take the first where
.orWhere('user.pseudo like :search', { search: `%${searchKey}%` })
.addOrderBy(filter === 'latest' ? 'topic.created_at' : 'topic.repliesCount', 'DESC')
.take(limit)
.skip(skip)
.getMany();
Run Code Online (Sandbox Code Playgroud)
生成的 SQL 查询是:
选择不同
distinctAlias。topic_id作为\ “ids_topic_id \”distinctAlias。topic_created_atFROM(SELECTtopic,idAStopic_id,topic。titleAStopic_title,topic。contentAStopic_content,topic。created_atAStopic_created_at,topic。viewsAStopic_views,topic。repliesCountAStopic_repliesCount,topic。categoryIdAStopic_categoryId,topic。userIdAStopic_userId,topic。surveyIdAStopic_surveyId,user。idASuser_id,user。user_email,user。pseudoASuser_pseudo,user。passwordASuser_password,user。rankASuser_rank,user。avatarASuser_avatar,user。createdAtAS .user_createdAt,userlastActivityASuser_lastActivity,user。signatureASuser_signature,user。post_countASuser_post_count,user。updatedAtASuser_updatedAtFROMtopictopicLEFT JOINuseruserONuser。id=topic.userIdAND (topic.userId =user.id) WHERE topic.categoryId = '5' ANDtopic.title像 '%admin%' OR topic.user.pseudo like '%admin%')distinctAliasORDER BYdistinctAlias。topic_created_atDESC,topic_idASC 限制 20
问题在这里:
WHERE topic.categoryId = '5' AND topic.title like '%admin%' OR topic.user.pseudo like '%admin%')
我期望 :
WHERE (topic.categoryId = '5' AND topic.title like '%admin%') OR (topic.categoryId = '5' AND topic.user.pseudo like '%admin%')
我想.orWhere正在或从.andWhere代替。凡
我没有找到有关此用例的任何文档/问题。
可以使用Brackets类控制查询条件的优先级:
topics = await topicRepository.createQueryBuilder('topic')
.leftJoinAndSelect('topic.user', 'user', 'topic.userId = user.id')
.where('topic.categoryId = :id', {
id: categoryId,
})
.andWhere(new Brackets(qb => {
qb.where('topic.title like :search', { search: `%${searchKey}%`})
orWhere('user.pseudo like :search', { search: `%${searchKey}%` });
}))
.addOrderBy(filter === 'latest' ? 'topic.created_at' : 'topic.repliesCount', 'DESC')
.take(limit)
.skip(skip)
.getMany();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2943 次 |
| 最近记录: |