typescript 如何执行类似查询 Typeorm

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47814537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:07:27  来源:igfitidea点击:

How to perform a like query Typeorm

javascripttypescripttypeorm

提问by Gardezi

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

大家好,我正在尝试查找所有包含 a 的结果。我尝试了几种方法,但问题是没有任何作用。它只返回一个空数组

  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

但没有任何效果。所有这些都返回给我一个空数组。有人能帮帮我吗谢谢

回答by pleerock

Correct way is:

正确的做法是:

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

回答by Gabriel Lupu

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

TypeORM 提供了开箱即用的Like功能。他们的文档中的示例

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

回答by GeorgiG

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

如果您已经使用 .find 方法来支持您的存储库需求,您可能不想切换到 QueryBuilder。

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

有一种使用 findConditions 实现 LIKE 过滤器的简单方法:

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

OR for case insensitive (in postgres):

或不区分大小写(在 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.

请记住,这很容易受到注入攻击,因此您必须明确保护动态值。

回答by Carlos Júlio

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

您还可以使用数据库函数进行连接。例如在 postgres 中:

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