typeorm查询条件: 当为空的时候不查询,当存在的时候查询

1、解决方法:…( )

userRepository.find({
   where: {
      status: 1,
      ...(params?.company && { company: params.company }),
   }
});

所以,如果params.company 是undefined(或空字符串)那么

...(undefined && { company: undefined })

返回undefined 并像…{} 一样为您销毁。

如果params.company 包含一些值,则

...('company' && { company: 'company' })

返回 …{company: ‘company’} 并为您的位置销毁它。

例子:

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、解决方法

	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 和 andWhere ,orWhere的使用

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();

你可能感兴趣的:(typeorm,前端,typeorm,where,andWhere,orWhere)