How to perform a like query TypeORM

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

var data = await getRepository(User)
  .createQueryBuilder("user")
  .where("user.firstName = %:name%", { name: firstName })
  .getMany();

and something like this

var data = await getRepository(User)
  .createQueryBuilder("user")
  .where("user.firstName like %:name%", { name: firstName })
  .getMany();

but nothing is working. All of these are returning me a empty array. Can somebody help me out thanks


Solution 1:

Correct way is:

 var data = await getRepository(User)
                  .createQueryBuilder("user")
                  .where("user.firstName like :name", { name:`%${firstName}%` })
                  .getMany();

Solution 2:

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}%`)
});

Solution 3:

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();