How to find entire string using typeORM, Nestjs, SQL Server, just like LIKE clause in mysql

667 views Asked by At

I have database called Beta and table called Keys. In that table I have a column licenseKey: string. I want to find the entire licenseKey from the portion of licenseKey.

Just like SQL below query:

SELECT * 
FROM KEYS 
WHERE licenseKey LIKE "%XYZ%"

I have following code in my controller file:

        @Get('getByLicenseKey/:licenseKey')
   async getByLicenseKey(@Param('licenseKey') licenseKey: string) {
        console.log('dsaadfad');
        return this.licenseKeyService.getKeyByLicenseKey(licenseKey);
    }

Service file

async getKeyByLicenseKey(licenseKey: string): Promise<keys[]> {
        return await this.keyRepo.find({ licenseKey: Like(`${licenseKey}`) });
}
2

There are 2 answers

1
Ronak Kansagra On BEST ANSWER

This works for me.

async getKeyByLicenseKey(licenseKey: string): Promise<keys[]> {
    return this.keyRepo.find({
        where:{licenseKey: Like(`%${licenseKey}%`)}
    })
}
0
Sudhagar B On

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

To perform a partial string search using TypeORM with NestJS and SQL Server, you can utilize the Like operator provided by TypeORM. Here's how you can modify your code:

import { Like } from 'typeorm';

async getKeyByLicenseKey(licenseKey: string): Promise<Key[]> {
  return await this.keyRepo.find({ licenseKey: Like(`%${licenseKey}%`) });
}

Make sure you import the Like operator from TypeORM. In the service file, you can use the Like operator with the % wildcard to search for the licenseKey value within the column. This will retrieve all records from the Keys table where the licenseKey column contains the specified licenseKey value as a substring.