如何动态添加 where 子句以查询使用 nestjs Query Builder 生成的子句?

How to add a where clause dynamically to query which is generated using nestjs Query Builder?

我正在开发 API,UI 的要求基于搜索字段的值,我将收到过滤后的结果。 UI.

上有很多搜索字段

示例代码-

  async getRoomsByMember(active: boolean, email: string): Promise<any[]> {
      return await getRepository(Room)
      .createQueryBuilder('room')
      .innerJoinAndSelect('room.member', 'member')
      .where("room.active = :active", {active: active})
      .andWhere("member.email = :email", { email: email })
      .getMany();
  }

如果用户在过滤字段中输入值,我将能够动态过滤房间成员,例如成员 phone 号码、城市、州、国家和邮政编码。

你快到了:-)

您可以尝试这样的操作:

async getRoomsByMember(active: boolean, email: string): Promise<any[]> {
  const query = getRepository(Room)
    .createQueryBuilder('room')
    .innerJoinAndSelect('room.member', 'member')
    .where("room.active = :active", {active: active});
  // Keep adding your other fields like member phone number, city, state, country, and zip, like below
  if(email) {
    query.andWhere("member.email = :email", { email: email })
  }
  return query.getMany();
}