Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 790
Gardezi Avatar asked Dec 14 '17 13:12

Gardezi


People also ask

What is Type ORM?

TypeORM is a TypeScript ORM (object-relational mapper) library that makes it easy to link your TypeScript application up to a relational database database. TypeORM supports MySQL, SQlite, Postgres, MS SQL Server, and a host of other traditional options.

Is TypeORM a database?

TypeORM supports multiple databases like MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana and WebSQL. TypeORM is an easy-to-use ORM to scaffold new apps that connect to databases. TypeORM functionality is RDBMS-specific concepts.


2 Answers

Correct way is:

 var data = await getRepository(User)
                  .createQueryBuilder("user")
                  .where("user.firstName like :name", { name:`%${firstName}%` })
                  .getMany();
like image 81
pleerock Avatar answered Oct 18 '22 21:10

pleerock


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}%`)
});
like image 90
Gabriel Lupu Avatar answered Oct 18 '22 23:10

Gabriel Lupu