这是我在项目中经常使用的解决方案。
我使用条件 spread syntax (...) 动态地“构建”查询。请参阅this 了解更多信息。
function findUsers(firstName?: string, lastName?: string): Promise<User[]> {
const userRepository = getRepository(User);
return userRepository.find({
where: {
...(firstName !== undefined && { firstName: firstName }),
...(lastName !== undefined && { lastName: lastName }),
}
});
}
请注意,这种方法考虑了大写和小写字母之间的差异(区分大小写)。例如。 John !== john.
使用示例:
// Find all users
const allUsers = await findUsers(undefined, undefined); // You can remove this by checking if both parameters are undefined and throw an error
// Find all users with 'John' as first name
const allUsersJohnFirstName = await findUsers("John", undefined);
// Find all users with 'Doe' as last name
const allUsersDoeLastName = await findUsers(undefined, "Doe");
// Find all users named 'John Doe'
const allUsersJohnDoe = await findUsers("John", "Doe");
如果您想要不区分大小写,请使用 ILike 运算符:
function findUsers(firstName?: string, lastName?: string): Promise<User[]> {
const userRepository = getRepository(User);
return userRepository.find({
where: {
...(firstName !== undefined && { firstName: ILike(firstName) }),
...(lastName !== undefined && { lastName: ILike(lastName) }),
}
});
}