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.
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.
Share Improve this question asked Nov 7, 2022 at 11:53 StormTrooperStormTrooper 1,5735 gold badges25 silver badges43 bronze badges2 Answers
Reset to default 8Have 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();
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: "pany.name",
searchTerm:"pany",
}
])
});