I have a query:
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();
Generated SQL query is:
SELECT DISTINCT
distinctAlias
.topic_id
as \"ids_topic_id\",distinctAlias
.topic_created_at
FROM (SELECTtopic
.id
AStopic_id
,topic
.title
AStopic_title
,topic
.content
AStopic_content
,topic
.created_at
AStopic_created_at
,topic
.views
AStopic_views
,topic
.repliesCount
AStopic_repliesCount
,topic
.categoryId
AStopic_categoryId
,topic
.userId
AStopic_userId
,topic
.surveyId
AStopic_surveyId
,user
.id
ASuser_id
,user
.user_email
,user
.pseudo
ASuser_pseudo
,user
.password
ASuser_password
,user
.rank
ASuser_rank
,user
.avatar
ASuser_avatar
,user
.createdAt
ASuser_createdAt
,user
.lastActivity
ASuser_lastActivity
,user
.signature
ASuser_signature
,user
.post_count
ASuser_post_count
,user
.updatedAt
ASuser_updatedAt
FROMtopic
topic
LEFT JOINuser
user
ONuser
.id
=topic
.userId
AND (topic.userId =user
.id
) WHERE topic.categoryId = '5' ANDtopic
.title
like '%admin%' OR topic.user.pseudo like '%admin%')distinctAlias
ORDER BYdistinctAlias
.topic_created_at
DESC,topic_id
ASC LIMIT 20
The problem is here:
WHERE topic.categoryId = '5' AND topic.title like '%admin%' OR topic.user.pseudo like '%admin%')
I expected :
WHERE (topic.categoryId = '5' AND topic.title like '%admin%') OR (topic.categoryId = '5' AND topic.user.pseudo like '%admin%')
I want the .orWhere being OR from .andWhere instead .where
I don't find any documentation / issue about this use case.
The precedence of query conditions can be controlled by using the Brackets class:
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();
(edit: added period to correct syntax)