添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

Ask Question

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

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.

This works for me.

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

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.