首页 > 其他分享 >Find Options

Find Options

时间:2024-03-26 11:00:48浏览次数:26  
标签:execute Options will following query WHERE Find SELECT

Find Options

# Basic options

All repository and manager .find* methods accept special options you can use to query data you need without using QueryBuilder:

  • select - indicates which properties of the main object must be selected
userRepository.find({
    select: {
        firstName: true,
        lastName: true,
    },
})

will execute following query:

SELECT "firstName", "lastName" FROM "user"
  • relations - relations needs to be loaded with the main entity. Sub-relations can also be loaded (shorthand for join and leftJoinAndSelect)
userRepository.find({
    relations: {
        profile: true,
        photos: true,
        videos: true,
    },
})
userRepository.find({
    relations: {
        profile: true,
        photos: true,
        videos: {
            videoAttributes: true,
        },
    },
})

will execute following queries:

SELECT * FROM "user"
LEFT JOIN "profile" ON "profile"."id" = "user"."profileId"
LEFT JOIN "photos" ON "photos"."id" = "user"."photoId"
LEFT JOIN "videos" ON "videos"."id" = "user"."videoId"

SELECT * FROM "user"
LEFT JOIN "profile" ON "profile"."id" = "user"."profileId"
LEFT JOIN "photos" ON "photos"."id" = "user"."photoId"
LEFT JOIN "videos" ON "videos"."id" = "user"."videoId"
LEFT JOIN "video_attributes" ON "video_attributes"."id" = "videos"."video_attributesId"
  • where - simple conditions by which entity should be queried.
userRepository.find({
    where: {
        firstName: "Timber",
        lastName: "Saw",
    },
})

will execute following query:

SELECT * FROM "user"
WHERE "firstName" = 'Timber' AND "lastName" = 'Saw'

Querying a column from an embedded entity should be done with respect to the hierarchy in which it was defined. Example:

userRepository.find({
    relations: {
        project: true,
    },
    where: {
        project: {
            name: "TypeORM",
            initials: "TORM",
        },
    },
})

will execute following query:

SELECT * FROM "user"
LEFT JOIN "project" ON "project"."id" = "user"."projectId"
WHERE "project"."name" = 'TypeORM' AND "project"."initials" = 'TORM'

Querying with OR operator:

userRepository.find({
    where: [
        { firstName: "Timber", lastName: "Saw" },
        { firstName: "Stan", lastName: "Lee" },
    ],
})

will execute following query:

SELECT * FROM "user" WHERE ("firstName" = 'Timber' AND "lastName" = 'Saw') OR ("firstName" = 'Stan' AND "lastName" = 'Lee')
  • order - selection order.
userRepository.find({
    order: {
        name: "ASC",
        id: "DESC",
    },
})

will execute following query:

SELECT * FROM "user"
ORDER BY "name" ASC, "id" DESC
  • withDeleted - include entities which have been soft deleted with softDelete or softRemove, e.g. have their @DeleteDateColumn column set. By default, soft deleted entities are not included.
userRepository.find({
    withDeleted: true,
})

find* methods which return multiple entities (findfindByfindAndCountfindAndCountBy) also accept following options:

  • skip - offset (paginated) from where entities should be taken.
userRepository.find({
    skip: 5,
})
SELECT * FROM "user"
OFFSET 5
  • take - limit (paginated) - max number of entities that should be taken.
userRepository.find({
    take: 10,
})

will execute following query:

SELECT * FROM "user"
LIMIT 10

** skip and take should be used together

** If you are using typeorm with MSSQL, and want to use take or limit, you need to use order as well or you will receive the following error: 'Invalid usage of the option NEXT in the FETCH statement.'

userRepository.find({
    order: {
        columnName: "ASC",
    },
    skip: 0,
    take: 10,
})

will execute following query:

SELECT * FROM "user"
ORDER BY "columnName" ASC
LIMIT 10 OFFSET 0
  • cache - Enables or disables query result caching. See caching for more information and options.
userRepository.find({
    cache: true,
})
  • lock - Enables locking mechanism for query. Can be used only in findOne and findOneBy methods. lock is an object which can be defined as:
{ mode: "optimistic", version: number | Date }

or

{
    mode: "pessimistic_read" |
        "pessimistic_write" |
        "dirty_read" |
        /*
            "pessimistic_partial_write" and "pessimistic_write_or_fail" are deprecated and
            will be removed in a future version.

            Use onLocked instead.
         */
        "pessimistic_partial_write" |
        "pessimistic_write_or_fail" |
        "for_no_key_update" |
        "for_key_share",

    tables: string[],
    onLocked: "nowait" | "skip_locked"
}

for example:

userRepository.findOne({
    where: {
        id: 1,
    },
    lock: { mode: "optimistic", version: 1 },
})

See lock modes for more information

Complete example of find options:

userRepository.find({
    select: {
        firstName: true,
        lastName: true,
    },
    relations: {
        profile: true,
        photos: true,
        videos: true,
    },
    where: {
        firstName: "Timber",
        lastName: "Saw",
        profile: {
            userName: "tshaw",
        },
    },
    order: {
        name: "ASC",
        id: "DESC",
    },
    skip: 5,
    take: 10,
    cache: true,
})

Find without arguments:

userRepository.find()

will execute following query:

SELECT * FROM "user"

# Advanced options

TypeORM provides a lot of built-in operators that can be used to create more complex comparisons:

  • Not
import { Not } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    title: Not("About #1"),
})

will execute following query:

SELECT * FROM "post" WHERE "title" != 'About #1'
  • LessThan
import { LessThan } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    likes: LessThan(10),
})

will execute following query:

SELECT * FROM "post" WHERE "likes" < 10
  • LessThanOrEqual
import { LessThanOrEqual } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    likes: LessThanOrEqual(10),
})

will execute following query:

SELECT * FROM "post" WHERE "likes" <= 10
  • MoreThan
import { MoreThan } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    likes: MoreThan(10),
})

will execute following query:

SELECT * FROM "post" WHERE "likes" > 10
  • MoreThanOrEqual
import { MoreThanOrEqual } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    likes: MoreThanOrEqual(10),
})

will execute following query:

SELECT * FROM "post" WHERE "likes" >= 10
  • Equal
import { Equal } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    title: Equal("About #2"),
})

will execute following query:

SELECT * FROM "post" WHERE "title" = 'About #2'
  • Like
import { Like } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    title: Like("%out #%"),
})

will execute following query:

SELECT * FROM "post" WHERE "title" LIKE '%out #%'
  • ILike
import { ILike } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    title: ILike("%out #%"),
})

will execute following query:

SELECT * FROM "post" WHERE "title" ILIKE '%out #%'
  • Between
import { Between } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    likes: Between(1, 10),
})

will execute following query:

SELECT * FROM "post" WHERE "likes" BETWEEN 1 AND 10
  • In
import { In } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    title: In(["About #2", "About #3"]),
})

will execute following query:

SELECT * FROM "post" WHERE "title" IN ('About #2','About #3')
  • Any
import { Any } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    title: Any(["About #2", "About #3"]),
})

will execute following query (Postgres notation):

SELECT * FROM "post" WHERE "title" = ANY(['About #2','About #3'])
  • IsNull
import { IsNull } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    title: IsNull(),
})

will execute following query:

SELECT * FROM "post" WHERE "title" IS NULL
  • ArrayContains
import { ArrayContains } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    categories: ArrayContains(["TypeScript"]),
})

will execute following query:

SELECT * FROM "post" WHERE "categories" @> '{TypeScript}'
  • ArrayContainedBy
import { ArrayContainedBy } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    categories: ArrayContainedBy(["TypeScript"]),
})

will execute following query:

SELECT * FROM "post" WHERE "categories" <@ '{TypeScript}'
  • ArrayOverlap
import { ArrayOverlap } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    categories: ArrayOverlap(["TypeScript"]),
})

will execute following query:

SELECT * FROM "post" WHERE "categories" && '{TypeScript}'
  • Raw
import { Raw } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    likes: Raw("dislikes - 4"),
})

will execute following query:

SELECT * FROM "post" WHERE "likes" = "dislikes" - 4

In the simplest case, a raw query is inserted immediately after the equal symbol. But you can also completely rewrite the comparison logic using the function.

import { Raw } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    currentDate: Raw((alias) => `${alias} > NOW()`),
})

will execute following query:

SELECT * FROM "post" WHERE "currentDate" > NOW()

If you need to provide user input, you should not include the user input directly in your query as this may create a SQL injection vulnerability. Instead, you can use the second argument of the Raw function to provide a list of parameters to bind to the query.

import { Raw } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    currentDate: Raw((alias) => `${alias} > :date`, { date: "2020-10-06" }),
})

will execute following query:

SELECT * FROM "post" WHERE "currentDate" > '2020-10-06'

If you need to provide user input that is an array, you can bind them as a list of values in the SQL statement by using the special expression syntax:

import { Raw } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findby({
    title: Raw((alias) => `${alias} IN (:...titles)`, {
        titles: [
            "Go To Statement Considered Harmful",
            "Structured Programming",
        ],
    }),
})

will execute following query:

SELECT * FROM "post" WHERE "titles" IN ('Go To Statement Considered Harmful', 'Structured Programming')

# Combining Advanced Options

Also you can combine these operators with below:

  • Not
import { Not, MoreThan, Equal } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    likes: Not(MoreThan(10)),
    title: Not(Equal("About #2")),
})

will execute following query:

SELECT * FROM "post" WHERE NOT("likes" > 10) AND NOT("title" = 'About #2')
  • Or
import { Not, MoreThan, ILike } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    title: Or(Equal("About #2"), ILike("About%")),
})

will execute following query:

SELECT * FROM "post" WHERE "title" = 'About #2' OR "title" ILIKE 'About%'
  • And
import { And, Not, Equal, ILike } from "typeorm"

const loadedPosts = await dataSource.getRepository(Post).findBy({
    title: And(Not(Equal("About #2")), ILike("%About%")),
})

will execute following query:

SELECT * FROM "post" WHERE NOT("title" = 'About #2') AND "title" ILIKE '%About%'

标签:execute,Options,will,following,query,WHERE,Find,SELECT
From: https://www.cnblogs.com/sexintercourse/p/18096117

相关文章

  • portfinder.getPort( { port: 8080, // 默认8080端口,若被占用,重复+1,直到找
    https://github.com/wkylin/pro-sale-charge/blob/df7fa93c8673701e6897f18498cab78a7fbb05d7/webpack/webpack.dev.js#L77C1-L92C3constportfinder=require('portfinder')module.exports=newPromise((resolve,reject)=>{portfinder.getPort(......
  • cmake之find_library使用问题
    附上工程源码demo工程PS:这个工程用于导出库CMakeLists.txtcmake_minimum_required(VERSION3.5)project(demoLANGUAGESCXX)set(CMAKE_INCLUDE_CURRENT_DIRON)set(CMAKE_CXX_STANDARD11)set(CMAKE_CXX_STANDARD_REQUIREDON)add_library(demoSHAREDdemo.cpp......
  • Error: Could not find or load main class org.apache.hadoop.hbase.util.GetJavaPro
    Hbase没有将其自身的依赖包添加到classpath配置路径所以才会导致找不到自身主类的报错vim/usr/local/hbase/bin/hbase 在161行出修改CLASSPATH="${HBASE_CONF_DIR}"CLASSPATH=${CLASSPATH}:$JAVA_HOME/lib/tools.jar:/usr/local/hbase/lib/*修改成功后,不再报错......
  • elFinder的目录映射
     目录映射一级文件夹创建符号连接;选择源链接点在elFinder相应文件夹的空白处右击,选择「创建为」→「符号连接」修改php\\connector.minimal.php文件,新增一个项目卷。大约是在165行之后。修改'path’一行中的路径修改'URL'一行中的路径(与path中的保持一致)//......
  • 常用命令find 细则
    常用命令find细则前言find命令在Linux和Unix系统中被广泛使用,用于在目录树中查找文件,并可以对查找到的文件执行指定的操作。以下是find命令的一些常用选项和用法总结:常用选项1.-name:按照文件名查找文件。2.-iname:按照文件名查找文件,不区分大小写。3.-type:......
  • find symbolic links
    -P永远不要跟随符号链接。这是默认行为。当find检查或打印有关文件的信息时,如果该文件是符号链接,则所使用的信息应从符号链接本身的属性中获取。 -L遵循符号链接。当find检查或打印有关文件的信息时,所使用的信息应取自链接指向的文件的属性,而不是链接本身(除非它是一个断开的......
  • nvm 下载新的Node(V18.19.0)版本,查看npm的版本出现异常Error: Cannot find module '@npm
    异常: 之前下载18.17.1查看npm也有问题ERROR:npmv9.6.7isknownnottorunonNode.jsv18.17.1. 大概意思是npm的版本是 v9.6.7单不能运行在v18.17.1的node上,但是node官网显示v18.17.1版本的node是适配v9.6.7的npm。这就很矛盾 最后找到的解决方案是升级nvm的版本......
  • Codeforces Round 923 (Div. 3) D. Find the Different Ones!
    写点简单的思维题https://codeforces.com/problemset/problem/1927/D思路:用两个数组,一个存储原始数据,一个用nex存该位置第一次不一样的下标#include<iostream>#include<vector>#include<algorithm>#include<math.h>#include<sstream>#include<string>#include<str......
  • find /path/to/search -type d -perm -o=x ! -perm -o=rw
    find/path/to/search-typed-perm-o=x!-perm-o=rwfind/-typed-perm-o=x!-perm/o=rw-execsh-c'find"$1"-typef-perm/o=r'sh{}\; find/-typed!-path'/data/data*'-perm-o=x!-perm/o=rw可以find/-typ......
  • 字符串匹配/查找字符串中子串存在次数/出现位置下标 问题----- {1.[find] 2.[substr]
    下文将介绍三种方法,求解问题类型:1.子串在主串中出现次数2.子串在主串中每次出现的下标位置以此题为例:题目链接:https://www.luogu.com.cn/problem/P8195解法一:kmp#include<iostream>#include<string>usingnamespacestd;constintN=1e6+10;intne[N];......