Search code examples
next.jsapi-designprisma

Search api prisma mysql where ANY


I'm trying to implement search api for my project. However I'm not sure how to accomplish this task whenever I got many variables which need to be included into query. For example how can I search for ANY character using this piece of code?

jobs = await prisma.jobOffer.findMany({
            where: {
                OR: [
                    {
                        title: {
                            search: searchTerm?.replace(' ', ' | ') || undefined
                        }
                    },
                    {
                        description: {
                            search: searchTerm?.replace(' ', ' | ') || undefined
                        }
                    }
                ]
            },
            include: {
                category: true,
                company: true
            }
        })

UPDATE: as stated in docs, OR returns no results if undefined. On the other hand, AND returns all results if undefined, so I took this approach:

jobs = await prisma.jobOffer.findMany({
        where: {
            AND: [ 
                   {
                       OR: [
                            {
                                title: {
                                    search: searchTerm?.replace(' ', ' | ') || undefined
                                }
                            },
                            {
                                 description: {
                                          search: searchTerm?.replace(' ', ' | ') || undefined
                                 }
                            }
                        ]
                   }
                 ]
        },
        include: {
            category: true,
            company: true
        }
    })

Solution

  • You are correct that if all conditions in OR operator are undefined then you will get no results (docs). I was under impression that you always have at least one condition there, but now I see that you are using one search term to check all the fields. In that case you can just check that searchTerm exists and then use OR operator, like that:

    jobs = await prisma.jobOffer.findMany({
          // Such condition is to make TS happy, considering `type searchTerm = string | undefined`
          where: !searchTerm ? undefined : {
            OR: [
              {
                title: {
                  search: searchTerm.replace(' ', ' | '),
                },
              },
              {
                description: {
                  search: searchTerm.replace(' ', ' | '),
                },
              },
            ],
          },
        });