Home > Back-end >  TypeORM query builder conditional where clause
TypeORM query builder conditional where clause

Time:11-08

I am trying to attach a conditional where clause to the query.

I need some link to documentation or any hint how can I acheive that.

Query:

const usersQuery = await connection
.getRepository(User)
.createQueryBuilder("user")
.getMany();

Now here I want to add if I get a userId paramater, I want to inject where clause into the query instance.

e.g:

if(params.userId){
   usersQuery.where("user.id = :id", { id: params.userId });
}

if(params.email){
   usersQuery.where("user.email= :email", { email: params.email});
}

This is something I want to achieve but some how I am unable to find this in the docs. Can anyone provide me the docs or reference.

CodePudding user response:

Have you tried this way?

const usersQuery = await connection
  .getRepository(User)
  .createQueryBuilder("user")

if(params.userId){
   usersQuery.andWhere("user.id = :id", { id: params.userId });
}

if(params.email){
   usersQuery.andWhere("user.email= :email", { email: params.email});
}

const users = await usersQuery.getRawMany();
  • Related