Rohit Gupta
Rohit Gupta

Reputation: 3261

How to query with 'OR' Operation in where object using find-options API in TypeORM

I want find results in my repo where firstname is like 'john' OR lastname is like 'doe' but findOptions where clause treat it as AND.

What I tried :

let results = await userRepo.find({
  where : {
    firstname : Like('%John%'),
    lastname : Like('%Doe%'),
  }
});

What I expect of this :

let results = await userRepo.find({
  where : {
    firstname : Like('%John%'),
    lastname : Or(Like('%Doe%')),
  }
});

Any help on how can I use OR within where object?

Upvotes: 8

Views: 25568

Answers (5)

Kumar Narayan
Kumar Narayan

Reputation: 21

const userRepository = getRepository(User);
/* return userRepository.find({
    email: ILike("%" + body.search + "%")
}); */

return userRepository.find({
    where : [{
        email : ILike("%"+body.search+"%"),
    }, {
        fullName : ILike("%"+body.search+"%"),
    }]
});

In my case working fine.

Upvotes: 2

Sajid Khaki
Sajid Khaki

Reputation: 161

 const query.where = await getRepository(abc)
  .createQueryBuilder("abc")
  .select(); 
 await query.where("abc.Name ILIKE :Name", {
    Name: `%${searchTerm}%`,
  }).orWhere("abc.description ILIKE :description", {
    description: `%${searchTerm}%`,
  });`

Upvotes: 0

noam steiner
noam steiner

Reputation: 4444

It is possible to use OR clause using the simple typeorm .find() options as described in TypeORM docs.

To query with OR operator you'll need to use an array of conditions instead of an object.

    let results = await userRepo.find({
        where: [
            { firstname: Like('%John%') },
            { lastname: Like('%Doe%') }
        ]
    });

Upvotes: 26

Rohit Gupta
Rohit Gupta

Reputation: 3261

So I found that I can also put a 'string' query for where in TypeORM.

I tried this :

let results = await userRepo.find({
   where : `firstname LIKE '%john%' OR lastname LIKE '%doe%'`
})

Until the feature comes out, I'll have to stick with this.

Upvotes: 0

yoz
yoz

Reputation: 952

I don't believe it's possible to write an OR clause using the simple typeorm .find() options:

https://github.com/typeorm/typeorm/blob/master/docs/find-options.md

Instead you'll have to use a QueryBuilder:

https://github.com/typeorm/typeorm/blob/master/docs/select-query-builder.md#adding-where-expression

This would look like

let results = await userRepo
  .createQueryBuilder()
  .select()
  .where("firstname LIKE %:first%", { first: John })
  .orWhere("lastname LIKE %:last%", { last: Doe });

Upvotes: 0

Related Questions