TypeORM,需要在查询条件中加上"WHERE IN (...)" & 只有当它有值时

TypeORM, need to add "WHERE IN (...)" in query condition & only when there is a value for it

我在用 TypeScript 编写的 node.js 项目中使用 TypeORM(版本 0.2.40)。我知道我可以从数据库中找到一条记录:

userRepository.find({ where: { firstName: "John", company: "foo" } });

它执行查询:

SELECT * FROM "user"
WHERE "firstName" = 'John' AND "company" = 'foo'

现在我在打字稿中有一个数组,它可能包含或可能不包含整数值:

 const userIds = params.user_ids; // e.g. undefined or [1,2,3]

如果 userIds 包含此类值,我希望我的查询添加 WHERE userIds IN (1,2,3) 否则不要添加此 where 条件。

我试过了(在这种情况下,params 可能包含 company,也可能不包含):


const {params} = parseRequest();

query: SelectQueryBuilder<MyEntity> = ...;

query.where({
  firstName: 'John',
  ...(params.company && { company: params.company }), // add 'company' condition only if value exists
}).andWhere({/* how to do here have 'WHERE IN (1,2,3)' if value exist?*/});

我有两个问题:

  1. 如何仅在 params.user_ids 存在时才添加“WHERE IN (...)”(与 params.company 相同)? (如果有巧妙的方法,请随时删除我的 andWhere 用法)

  2. 假设值存在,TypeORM 为 params.user_ids 添加“WHERE IN (...)”逻辑的语法是什么?

您可以将简单的条件与 IN 运算符一起使用。 例如

import {In} from "typeorm";

let query = ...
if (userIds?.length) {
  // WHERE IN [...userIds]
  query = query.where({userId: In([...userIds])})
}
// Continue chaining.
query = ...

资源: