Reputation: 1321
I want to query a post with id, slug, username, userId params. at least one of the param value are exists in the queries. Not required all of one.
const post = await prisma.post.findFirst({
where: {
OR: [
{
AND: [
{ published: true },
{
OR: [
{ id },
{
AND: [
{ slug },
{
author: {
profile: {
username
}
}
}
]
}
]
}
]
},
{
authorId: userId || undefined
}
]
},
...select
})
Database data (posts):
[{id: 1, published: false}, {id: 2, published: true}]
Query param is id: 1
but output is:
{id: 2, published: true}
Is there any wrong with my query?
Prisma Post model:
model Post {
id String @id @default(cuid())
title String
body String
slug String
published Boolean
draft Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId String
}
User model:
model User {
id String @id @default(cuid())
name String
email String @unique
password String?
posts Post[]
profile Profile?
}
Profile model:
model Profile {
id String @id @default(cuid())
bio String?
author User? @relation(fields: [authorId], references: [id])
authorId String?
phone String?
username String?
}
Upvotes: 0
Views: 1246
Reputation: 7278
Based on the explanation you have provided in the comments, you want to:
Query a post with id, slug, username, userId
one or more of which may be null or undefined for a single query. In case a field is null/undefined, that field ought to be ignored for the particular query.
Before I go onto the solution, you need to know that null
and undefined
have special meaning in Prisma.
null
is a valueundefined
means do nothingSo basically, if you provide undefined for any field, it is effectively ignored. More info about this here
Knowing this information, you need to convert null
values in your paramter arguments to undefined
, as you simply want to ignore the field in that particular query. You can set up your query as follows:
async function foo(params) {
const { id, slug, username, userId } = params;
const post = await prisma.post.findFirst({
where: {
id: id ? id : undefined,
slug: slug ? slug : undefined,
authorId: userId ? userId : undefined,
author: username
? {
profile: {
username: username,
},
}
: undefined,
},
});
}
Upvotes: 0
Reputation: 386
Nest the query filters inside an OR clause.
const { id, slug, username, userId } = params;
const posts = await prisma.post.findFirst({
where: {
OR: [
{ id },
{ slug },
{ author: { profile: { username } } },
{ authorId: userId }
]
}
});
Upvotes: 0