期望 orWhere() 与 andWhere() 一起使用,而不是 where()

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 查询是:

选择不同distinctAliastopic_id作为\ “ids_topic_id \” distinctAliastopic_created_atFROM(SELECT topicidAS topic_idtopictitleAS topic_titletopiccontentAS topic_contenttopiccreated_atAS topic_created_attopicviewsAS topic_viewstopicrepliesCountAS topic_repliesCounttopiccategoryIdAS topic_categoryIdtopicuserIdAS topic_userIdtopicsurveyIdAS topic_surveyIduseridAS user_iduseremailAS user_emailuserpseudoAS user_pseudouserpasswordAS user_passworduserrankAS user_rankuseravatarAS user_avatarusercreatedAtAS .user_createdAt ,userlastActivityAS user_lastActivityusersignatureAS user_signatureuserpost_countAS user_post_countuserupdatedAtAS user_updatedAtFROM topic topicLEFT JOIN user userON userid= topic. userIdAND (topic.userId = user. id) WHERE topic.categoryId = '5' AND topic. title像 '%admin%' OR topic.user.pseudo like '%admin%') distinctAliasORDER BY distinctAliastopic_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代替。凡

我没有找到有关此用例的任何文档/问题。

iY1*_*1NQ 6

可以使用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)