How to perform a like query Typeorm

后端 未结 5 474
北海茫月
北海茫月 2020-12-30 22:40

Hello guys I\'m trying to find all the results that have a in them. I have tried a couple of ways but the problem is nothing works. It just returns an empty array

相关标签:
5条回答
  • 2020-12-30 23:07

    TypeORM provides out of the box Like function. Example from their docs:

    import {Like} from "typeorm";
    
    const loadedPosts = await connection.getRepository(Post).find({
        title: Like("%out #%")
    });
    

    in your case:

    var data = await getRepository(User).find({
        name: Like(`%${firstName}%`)
    });
    
    0 讨论(0)
  • 2020-12-30 23:07

    You can also use the database function for concatenation. In postgres for instance:

     var data = await getRepository(User)
                  .createQueryBuilder("user")
                  .where("user.firstName like '%' || :name || '%'", {name: firstName })
                  .getMany();
    
    0 讨论(0)
  • 2020-12-30 23:20
    var data = await  getRepository(User)
                            .createQueryBuilder("user")
                            .where("user.firstName ILIKE %q, {q:`%${VALUE_HERE}%` })
                    .getMany();
    

    This is how I do it. Hope it helps

    0 讨论(0)
  • 2020-12-30 23:28

    Correct way is:

     var data = await getRepository(User)
                      .createQueryBuilder("user")
                      .where("user.firstName like :name", { name:`%${firstName}%` })
                      .getMany();
    
    0 讨论(0)
  • 2020-12-30 23:28

    If you have already used .find methods to support your repository needs you might not want to switch to QueryBuilder.

    There is an easy way to implement LIKE filter using findConditions:

    this.displayRepository.find({ where: "Display.name LIKE '%someString%'" });
    

    OR for case insensitive (in postgres):

    this.displayRepository.find({ where: "Display.name ILIKE '%someString%'" });
    

    Keep in mind this is susceptible to Injection attacks, so you must protect the dynamic value explicitly.

    0 讨论(0)
提交回复
热议问题