앞으로 등장할 코드에서 prisma 변수는 const prisma = new PrismaClient() 를 의미합니다.
mysql 사용 기준으로 작성되어 몇몇 기능 및 지원에 대한 내용이 없을 수 있습니다.
Query Option
where : 필드 필터링
- filters
// equals: 값이 n 과 동일한 경우
const result = await prisma.user.findMany({
where: {
name: { equals: 'Eleanor' }, // or name: 'Eleanor'
},
});
// not: 값이 n과 다른 경우
await prisma.user.findMany({
where: {
OR: [
{ name: { not: 'Eleanor' } },
{ name: null } // * NULL 값은 포함하지 않으므로 포함하기 위해서는 OR 연산자를 사용하여 NULL 값을 추가해 처리
]
}
})
// in: 값 n 이 목록에 있는 경우 (null 값은 반환되지 않습니다.)
const getUser = await prisma.user.findMany({
where: {
id: { in: [22, 91, 14, 2, 5] },
},
});
// notIn: 값 n이 목록에 없는 경우 (null 값은 반환되지 않습니다.)
const getUser = await prisma.user.findMany({
where: {
id: { notIn: [22, 91, 14, 2, 5] },
},
});
// lt: 값 n은 x보다 작은 경우
const getPosts = await prisma.post.findMany({
where: {
likes: { lt: 9 }, // likes < 9
},
});
// gt: 값 n은 x보다 큰 경우
const getPosts = await prisma.post.findMany({
where: {
likes: { gt: 9 }, // likes > 9
},
});
// contains: 값 n 에 x 가 포함되는 경우
const result = await prisma.post.count({
where: {
content: { contains: 'databases' },
},
});
// NOT + contains: 값 n 에 x 가 포함되지 않는 경우
const result = await prisma.post.count({
where: {
NOT: { // NOT operators
content: { contains: 'databases' },
},
},
});
// search: 문자열 필드 내에서 검색 옵션 (FTS: Full Text Search 지원)
// ※ FTS(Full-Text Search) : 텍스트 데이터를 효율적으로 검색하기 위한 검색 기술로 단순히 문자열을 비교하는 방식이 아니라, 텍스트의 의미, 구조, 그리고 패턴을 분석하여 관련성 높은 결과를 빠르게 반환하여 대량의 텍스트 데이터를 검색해야 하는 애플리케이션에서 중요한 역할을 합니다.
const result = await prisma.post.findMany({
where: {
title: { search: 'cat | dog' }, // title 에 'cat' or 'dog' 포함된 모든 게시물
// title: { search: 'cat & dog' }, title 에 'cat' and 'dog' 포함된 모든 게시물
// title: { search: '!cat' }, title 에 'cat'가 포함되지 않은 모든 게시물
},
});
// startsWith: x 로 시작하는 n 레코드
const result = await prisma.post.findMany({
where: {
title: { startsWith: 'Pr' },
},
});
// endsWith: x 로 끝나는 n 레코드
const result = await prisma.user.findMany({
where: {
email: { endsWith: 'prisma.io' },
},
});
- operators
// AND: 모든 조건은 true 를 반환하는 경우
const result = await prisma.post.findMany({
where: {
AND: [
{
content: { contains: 'Prisma' },
},
{
published: { equals: false },
},
],
},
});
// where 조건에 AND는 기본적으로 포함되어 있는 것으로 간주하므로 위 예제와 동일
const result = await prisma.post.findMany({
where: {
content: { contains: 'Prisma' },
published: { equals: false },
},
});
// OR: 하나 이상의 조건이 true 를 반환하는 경우
const result = await prisma.post.findMany({
where: {
OR: [
{
title: { contains: 'Prisma' },
}, {
title: { contains: 'databases' },
},
],
},
});
// NOT: 모든 조건이 false를 반환하는 경우
const result = await prisma.post.findMany({
where: {
NOT: {
title: { contains: 'SQL' },
},
},
});
// 연산자(예: NOT 및 OR)를 사용하여 여러 조건을 조합하여 필터링할 수 있습니다.
const result = await prisma.post.findMany({
where: {
OR: [
{
title: { contains: 'Prisma', },
},
{
title: { contains: 'databases' },
},
],
NOT: {
title: { contains: 'SQL' },
},
// relate field 인 user 를 필수적으로 include 를 하지 않아도 필터링에 사용 가능, prisma 는 관계된 필드의 조건을 SQL `JOIN`으로 변환하여 실행합니다.
user: {
NOT: {
email: { contains: 'sarah' },
},
},
},
});
- relation filters
// Filter on "-to-many" relations (some, every, none)
// some: 해당 관계 모델의 레코드 목록 중 하나 이상의 레코드가 필터링 기준과 일치하는 경우 true 반환
// 해석: user 와 관계된 post 목록 중 하나 이상의 post 라도 some 하위 조건을 모두 만족하는 경우(content 에 "Prisma" 를 포함하는 경우)의 user 레코드 목록을 반환
const result = await prisma.user.findMany({
where: {
post: { // relation field
some: {
content: { contains: "Prisma" }
}
}
}
}
// every: 해당 관계 모델의 레코드 목록 중 모든 레코드가 필터링 기준과 일치하는 경우 true 반환
// 해석: user 와 관계된 post 목록 중 모든 post 가 every 하위 조건을 모두 만족하는 경우(content 에 "Prisma" 를 포함하는 경우)의 user 레코드 목록을 반환
const result = await prisma.user.findMany({
where: {
post: { // relation field
every: { published: true },
}
}
}
// none: 해당 관계 모델의 레코드 목록 중 어떤 하나의 레코드 즉 모든 레코드가 필터링 기준과 일치하지 않는 경우 true 반환 (every 반대 버전)
const result = await prisma.user.findMany({
where: {
post: {
none: { published: true } // 게시된 게시물이 없는 경우
}
}
}
// Filter on "-to-one" relationss (some, every, none)
// is: 해당 관계 모델의 단일 레코드가 필터링 기준과 일치하는 경우 true 반환
const result = await prisma.post.findMany({
where: {
user: {
is: { name: "Bob" },
}
}
}
// isNot: 해당 관계 모델의 단일 레코드가 필터링 기준과 일치하지 않는 경우 true 반환
const result = await prisma.post.findMany({
where: {
user: {
is: { name: "Bob" },
}
}
}
orderBy : 정렬
const users = await prisma.user.findMany({
orderBy: { email: 'asc' },
nulls: ['first' | 'last'] // null 값을 정렬 순서에서 처음에 표시할지, 아니면 마지막으로 표시할지 제어할 수 있습니다.
});
// 관계 필드 기준으로 정렬
const getActiveusers = await prisma.user.findMany({
orderBy: {
posts: { count: 'desc' },
},
});
// 중첩 모델 레코드 정렬
const usersWithPosts = await prisma.user.findMany({
orderBy: { email: 'asc' },
include: {
posts: {
select: { title: true },
orderBy: { title: 'asc' },
},
},
});
// 관계 집계 값으로 정렬
const getActiveUsers = await prisma.user.findMany({
orderBy: {
posts: { _count: 'desc' },
},
})
distinct: 중복 제거
const distinctCities = await prisma.user.findMany({
select: {
city: true,
country: true,
},
distinct: ['city', 'country'],
});
참고
https://www.prisma.io/docs/orm/reference/prisma-client-reference#where
https://www.prisma.io/docs/orm/reference/prisma-client-reference#filter-conditions-and-operators
https://www.prisma.io/docs/orm/reference/prisma-client-reference#relation-filters
'Prisma' 카테고리의 다른 글
[Prisma] 6. Pagination & Aggregation (0) | 2025.01.18 |
---|---|
[Prisma] 5. Nested Queries (0) | 2025.01.17 |
[Prisma] 3. Prisma query 사용 (CRUD, query options) (0) | 2025.01.14 |
[Prisma] 2. Prisma Model 디테일 (0) | 2025.01.12 |
[Prisma] 1. Prisma 란 무엇인가? (0) | 2025.01.11 |