P
Prismaā€¢2w ago
toadmilk

[Noob] how do you add a optional search param to a findMany.

want it to match the title or content if provided otherwise match everything.
2 Replies
Prisma AI Help
Prisma AI Helpā€¢2w ago
You selected the bot's instantaneous insights. Let me compile your answer right away! To add an optional search parameter to a findMany query that matches the title or content if provided, or matches everything otherwise, you can use the OR operator in Prisma. Here's how you can structure your query:
const result = await prisma.post.findMany({
where: {
OR: [
{
title: {
contains: searchText,
},
},
{
content: {
contains: searchText,
},
},
],
},
});
const result = await prisma.post.findMany({
where: {
OR: [
{
title: {
contains: searchText,
},
},
{
content: {
contains: searchText,
},
},
],
},
});
However, to make this search parameter optional, you need to conditionally include the where clause based on whether searchText is provided or not. Here's how you can modify the query:
const result = await prisma.post.findMany({
where: searchText
? {
OR: [
{
title: {
contains: searchText,
},
},
{
content: {
contains: searchText,
},
],
},
}
: {},
});
const result = await prisma.post.findMany({
where: searchText
? {
OR: [
{
title: {
contains: searchText,
},
},
{
content: {
contains: searchText,
},
],
},
}
: {},
});
In this query: - If searchText is provided (truthy), the where clause will include the OR condition to search in both title and content. - If searchText is not provided (falsy, e.g., undefined or an empty string), an empty object {} is used as the where condition, which will match all records. This approach ensures that when no search text is provided, the query will return all posts, and when a search text is provided, it will filter the posts based on the title or content containing the search text. Prisma Client API reference provides more information on using the OR operator in Prisma queries. āœ… Great, thanks for letting us know that this solved your question!
Nurul
Nurulā€¢2w ago
Glad to hear that the bot was helpful šŸ™Œ

Did you find this page helpful?