【问题标题】:LIKE query with wildcard in TypeORM QueryBuilder在 TypeORM QueryBuilder 中使用通配符进行 LIKE 查询
【发布时间】:2018-08-30 15:35:55
【问题描述】:

在我的 NestJS 项目中,我有这个 TypeORM 查询:

const users = await this.usersRepository.find({
  skip,
  take,
  order: sortingObject,
  join: {
      alias: 'user',
      leftJoinAndSelect: {
          country: 'user.country_id',
      },
  },
});

现在我只想返回名称中带有John 的用户。在 SQL 中,这将是一个 LIKE 查询 LIKE %John%

https://github.com/typeorm/typeorm/blob/master/docs/find-options.md 中没有关于通配符LIKE 查询的信息。

How to perform a like query Typeorm 给出了一个解决方案: .where("user.firstName like :name", {name: '%' + firstName + '%' })

但是我无法使用skiptake,这在使用where() 而不是find() 时可用。

对我如何使用 TypeORM QueryBuilder 实现这一点有任何想法吗?

【问题讨论】:

    标签: nestjs typeorm typeorm-datamapper


    【解决方案1】:

    QueryBuilder 中有分页方法(.skip(int).take(int))。

    试试这样的。

    const users = await this.usersRepository
        .createQueryBuilder("user")
        .leftJoinAndSelect("user.country_id", "country")
        .skip(5)
        .take(10)
        .where("user.firstName like :name", {name: '%' + firstName + '%' })
        .orderBy("user.id", "DESC")
        .getMany();
    

    详情请参考文档: Using Pagination in TypeORM QueryBuilder

    【讨论】:

    • 我的问题不是如何使用 skip/take 方法,而是如何结合通配符 LIKE 查询使用这些方法
    • 您只需将问题中的.where("user.firstName like :name", {name: '%' + firstName + '%' }) 添加到@michael-lam 在上面发布的查询构建器链中...createQueryBuilder("user").getMany() 行之间的任何位置。
    • 感谢@Timshel 的补充。编辑了答案
    猜你喜欢
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 2019-06-07
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    相关资源
    最近更新 更多