prismaprisma2

Prisma Typescript where clause inside include?


I am trying to query the database (Postgres) through Prisma. My query is

const products = await prisma.products.findMany({
  where: { category: ProductsCategoryEnum[category] },
  include: {
    vehicles: {
      include: {
        manufacturers: { name: { in: { manufacturers.map(item => `"${item}"`) } } },
      },
    },
  },
});

The error message is

Type '{ name: { in: { manufacturers: string; "": any; }; }; }' is not assignable to type 'boolean | manufacturersArgs'. Object literal may only specify known properties, and 'name' does not exist in type 'manufacturersArgs'.ts(2322)

Manufacturers have the field name and it is unique; I am not sure why this is not working or how I can update this code to be able to query the database. It is like I should cast the values into Prisma arguments.


Solution

  • The TypeScript error is pretty self-explanatory: the name property does not exist in manufacturersArgs. The emitted Prisma Client does a great job of telling you what properties do and do not exist when filtering.

    If you are trying to perform a nested filter, you need to use select instead of include.

    Documentation: https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#filter-a-list-of-relations

    Your query is going to look something like this:

    const products = await prisma.products.findMany({
      where: { category: ProductsCategoryEnum[category] },
      select: {
        // also need to select any other fields you need here
        vehicles: {
          // Updated this
          select: { manufacturers: true },
          // Updated this to add an explicit "where" clause
          where: {
            manufacturers: { name: { in: { manufacturers.map(item => `"${item}"`) } } },
          },
        },
      },
    });
    

    The final code ultimately depends on your Prisma schema. If you are using an editor like VS Code, it should provide Intellisense into the Prisma Client's TypeScript definitions. You can use that to navigate the full Prisma Client and construct your query based on exactly what is and is not available. In VS Code, hold control [Windows] or command [macOS] and click on findMany in prisma.products.findMany. This lets you browse the full Prisma Client and construct your query!