1. Solution: ...( )
userRepository.find({
where: {
status: 1,
...(params?.company && { company: params.company }),
}
});
So, if params.company is undefined (or empty string) then
...(undefined && { company: undefined })
Returns undefined and destroys it for you like ...{}.
If params.company contains some value, then
...('company' && { company: 'company' })
Return ...{company: 'company'} and destroy it for your location.
example:
const companyTestWithValue = 'company';
const companyTestWithoutValue = '';
const whereWithValue = {
status: 1,
...(companyTestWithValue && { company: companyTestWithValue }),
};
const whereWithoutValue = {
status: 1,
...(companyTestWithoutValue && { company: companyTestWithoutValue }),
};
console.log('whereWithValue:', whereWithValue);
console.log('whereWithoutValue:', whereWithoutValue);
2. Solution
import { User } from "./../user/entities/user.entity"
let res = await this.articleRepository.createQueryBuilder()
.leftJoinAndSelect(
User,
"user",
"article.author_id = user.user_id"
)
.select(`
article.article_id as articleId,
article.title as title,
date_format(article.update_time, '%Y-%m-%d %T') as updateTime,
article.status as status,
user.user_name as authorName
`)
.where(new Brackets((qb) => {
if (body.authorName) {
return qb.where(`user.user_name = ${body.authorName}`)
} else {
return qb;
}
}))
.andWhere(new Brackets((qb) => {
if (body.updateTimeStart && body.updateTimeEnd) {
return qb.andWhere('article.update_time BETWEEN :start AND :end', {
start: new Date(body.updateTimeStart),
end: new Date(body.updateTimeEnd)
})
} else {
return qb;
}
}))
// .where(`user.user_name = ${body.authorName}`)
// .andWhere('article.update_time BETWEEN :start AND :end', {
// start: new Date(body.updateTimeStart),
// end: new Date(body.updateTimeEnd)
// })
.andWhere({
...(body.sectionId && { sectionId: body.sectionId }),
...(body.sectionSubId && { sectionSubId: body.sectionSubId })
})
.orderBy("updateTime", "ASC")
.skip(1)
.take(20)
.getRawMany();
Where and andWhere, orWhere use
const categories: CategoryEntity[] = await getManager()
.createQueryBuilder(CategoryEntity, 'tsk')
.where(new Brackets((qb) => qb.where('tsk.category = DEFAULT').andWhere('tsk.status = NEW')))
.orWhere(new Brackets((qb) => qb.where('tsk.category = REVIEW').andWhere('tsk.status = OPEN')))
.orWhere(new Brackets((qb) => qb.where('tsk.category = DEFAULT').andWhere('tsk.status = "IN PROGRESS"')))
.getMany();