如何在 TypeORM 中使用 find-options API 查询对象中的 'OR' 操作

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

我想在我的 repo 中找到名字像 'john' 姓氏像 'doe' 的结果 但 findOptions where 子句将其视为 AND。

我尝试了什么:

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

我对此的期望:

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

关于如何在 where 对象中使用 OR 的任何帮助?

我认为不可能使用简单的 typeorm .find() 选项编写 OR 子句:

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

相反,您必须使用 QueryBuilder:

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

这看起来像

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

所以我发现我也可以在 TypeORM 中查询 'string' where。

我试过了:

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

在该功能出来之前,我将不得不坚持下去。

可以使用简单的 typeorm .find() 选项来使用 OR 子句,如 TypeORM docs 中所述。

要使用 OR 运算符进行查询,您需要使用条件数组而不是对象。

    let results = await userRepo.find({
        where: [
            { firstname: Like('%John%') },
            { lastname: Like('%Doe%') }
        ]
    });
 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}%`,
  });`
const userRepository = getRepository(User);
/* return userRepository.find({
    email: ILike("%" + body.search + "%")
}); */

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

在我的情况下工作正常。