Search code examples
javascriptnode.jsnestjsprisma

Prisma findMany where relationship is not null


I have these two low-end models and I want to list all their subcategories with their menus, provided that the menu is not empty.

model SubCategory {
  id         Int        @id @default(autoincrement())
  label      String
  image      String
  categories Category[] @relation("CategoryToSubCategory")
  menu       Menu[]     @relation("MenuToSubCategory")
  createdAt  DateTime   @default(now())
  updatedAt  DateTime   @updatedAt
}

model Menu {
  id                     Int                     @id @default(autoincrement())
  name                   String                  @db.VarChar(64)
  description            String                  @db.Text
  favoriteMenus          FavoriteMenus[]
  ingredients            Ingredients[]
  createdAt              DateTime                @default(now())
  updatedAt              DateTime                @updatedAt

  @@index([chefStoreId], map: "Menu_chefStoreId_fkey")
  @@fulltext([name, description])
}

The query I am writing is as follows:

const topCategories = await this.prisma.subCategory.findMany({
  include: {
    menu: {
      where: {
        id: { not: null },
      },
    },
  },
  orderBy: {
    id: 'desc',
  },
  take: 50,
});

But it gives me the error "Argument not must not be null."


Solution

  • I mean, menu won't ever be null because it's an array, it will be just an empty array. Menu id also can't be null in your schema.

    But if you mean that you want to find subCategory which has at least 1 menu attached, then I think you need to use some relation filter with empty params (docs):

      const topCategories = this.prisma.subCategory.findMany({
        where: {
          menu: {
            some: {},
          },
        },
        include: {
          menu: true,
        },
        orderBy: {
          id: 'desc',
        },
        take: 50,
      });