StormTrooper
StormTrooper

Reputation: 1573

TypeORM query builder conditional where clause

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.

Upvotes: 2

Views: 3905

Answers (2)

Gabriel H. Kubota
Gabriel H. Kubota

Reputation: 13

check a npm package called typeorm-difo. The plugin's goal is to facilitate writing "relations", "where" and "order" arguments for any find method of an entity repository. With this plugin, it is not necessary to manually write the "relation" argument, it is inferred from the "where" argument. It is also possible to reduce nested objects by concatenating them with "." (period).

 userRepository.find({
     where: getWhere([
         {
             field: "firstName",
             searchTerm:"John",
         },
         {
             field: "company.name",
             searchTerm:"company",
         }
     ])
 });

Upvotes: 0

vicki
vicki

Reputation: 470

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

Upvotes: 8

Related Questions