본문 바로가기
프로그래밍/TypeORM

[TypeORM] Find Options - Basic Options

by YuminK 2023. 9. 2.

https://orkhan.gitbook.io/typeorm/docs/find-options

 

Basic options

모든 레포지토리와 manager .find* 메소드는 데이터 쿼리를 위한 특별한 옵션을 받는다. 

 

select - 선택되어야 하는 메인 객체를 지정하는 속성

userRepository.find({
    select: {
        firstName: true,
        lastName: true,
    },
})

 

SELECT "firstName", "lastName" FROM "user"

 

relations - 메인 엔티티와 같이 로드되어야 한다. 서브 릴레이션 또한 사용될 수 있다.

(join과 leftJoinAndSelect의 약어이다.)

 

userRepository.find({
    relations: {
        profile: true,
        photos: true,
        videos: true,
    },
})
userRepository.find({
    relations: {
        profile: true,
        photos: true,
        videos: {
            videoAttributes: true,
        },
    },
})

 

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 - 어떠한 엔티티가 쿼리 되어야 하는지에 대한 조건

userRepository.find({
    where: {
        firstName: "Timber",
        lastName: "Saw",
    },
})

 

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

 

임베디드 엔티티를 쿼리하는 경우, 하이어라키 구조대로 처리되어야 한다.

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

 

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

 

OR 연산자 처리

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

 

SELECT * FROM "user" WHERE ("firstName" = 'Timber' AND "lastName" = 'Saw') OR ("firstName" = 'Stan' AND "lastName" = 'Lee')

 

order - 정렬

userRepository.find({
    order: {
        name: "ASC",
        id: "DESC",
    },
})

 

SELECT * FROM "user"
ORDER BY "name" ASC, "id" DESC

 

withDeleted - soft-delete 처리된 엔티티를 포함한다. 일반적으로는 처리되지 않는다. 

userRepository.find({
    withDeleted: true,
})

 

find* 메소드는 여러 엔티티를 반환한다. (find, findBy, findAndCount, findAndCountBy) 또한 다음 옵션을 처리한다.

 

skip - offset, 엔티티가 처리되는 위치

userRepository.find({
    skip: 5,
})

 

SELECT * FROM "user"
OFFSET 5

 

take - 가져오는 엔티티의 최대 수를 제한한다.

userRepository.find({
    take: 10,
})

 

SELECT * FROM "user"
LIMIT 10

 

만약 MSSQL을 typeorm과 같이 사용하고 있고 take 또는 limit을 사용하길 원하는 경우 정렬(order)또한 사용할 필요가 있다. 아니라면 에러 메시지를 얻는다. ('Invalid usage of the option NEXT in the FETCH statement.')

 

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

 

SELECT * FROM "user"
ORDER BY "columnName" ASC
LIMIT 10 OFFSET 0

 

cache - 결과 캐싱 여부

userRepository.find({
    cache: true,
})

 

lock - 잠금 매커니즘을 활성화한다. 오직 findOne과 findOneBy메소드에서 사용될 수 있다. 

lock은 이렇게 정의 될 수 있는 오브젝트이다. 

{ mode: "optimistic", version: number | Date }

 

또는

{
    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"
}

 

예시)

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

 

종합 예제)

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,
})

 

전체 조회하기

userRepository.find()

 

SELECT * FROM "user"

'프로그래밍 > TypeORM' 카테고리의 다른 글

[TypeORM] One-to-one relations  (0) 2023.09.03
[TypeORM] Find Options - Advanced options  (0) 2023.09.02
[TypeORM] EntityManager API  (0) 2023.09.02
[TypeORM] Delete using Query Builder  (0) 2023.09.02
[TypeORM] Insert using Query Builder  (0) 2023.09.02

댓글