【问题标题】:How would I do a search with two columns in PostgreSQL (TypeORM)?如何在 PostgreSQL (TypeORM) 中使用两列进行搜索?
【发布时间】:2022-01-20 19:51:58
【问题描述】:

我目前正在研究如何在我的项目中实施搜索。我有一个名为 users 的表,它有两列,firstName 和 lastName。我希望能够在这两列之间进行搜索,例如用户的名字是 John,姓氏是 Smith,所以当他们搜索 John Smith 时,它会返回具有该名称的用户。

或者他们可以只搜索名字等。有什么方法可以解决这个问题?

在这里利用 PostgreSQL 的全文功能是正确的途径吗?我目前在这里使用带有 TypeORM 和 PostgreSQL 的 Node。

【问题讨论】:

    标签: node.js postgresql typeorm


    【解决方案1】:

    这是我在项目中经常使用的解决方案。

    我使用条件 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) }),
          }
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多