如何在Prisma中正确使用“AND”运算符?

问题描述 投票:0回答:2

我有 2 个型号。数据库管理系统 Postgres

model Product {
 id          Int      @id @default(autoincrement())
 name        String   @unique
 description String?
 options     Option[]

 @@map("products")
}

model Option {\
 id                      Int     @id @default(autoincrement())
 title                   String?
 description             String?
 productId               Int
 product                 Product @relation(fields: [productId], references: [id]
 @@map("options")
}

我想通过相关表“选项”过滤“产品”,为此我使用以下表达式

const product = await this.prismaService.product.findMany({
        where: {
            options: {
                some: {
                    AND: [
                        {
                            title: 'square',
                            description: '20',
                        },
                        {
                            title: 'type',
                            description: 'invertor',
                        },
                    ],
                },
            },
        },
        include: { options: true },
    });

使用这个表达式,我将得到一个空数组,并且“OR”运算符将按其应有的方式工作。即使我将一个对象放入“AND”数组中,我也会得到正确的过滤。请指出我做错了什么并帮助我解决问题。

javascript postgresql next.js orm prisma
2个回答
0
投票

问题似乎可能与您在 some 过滤器中使用 AND 运算符的方式有关。 some 过滤器旨在检查数组中是否至少有一个元素满足条件,并且其中的 AND 运算符可能无法按预期工作。

您可以尝试以下更新版本

const product = await this.prismaService.product.findMany({
  where: {
    options: {
      every: {
        OR: [
          { title: 'square', description: '20' },
          { title: 'type', description: 'invertor' },
        ],
      },
    },
  },
  include: { options: true },
});

我用 every 过滤器替换了 some 过滤器,并在其中使用了 OR 条件。这应该找到至少有一个具有指定标题和描述的选项的产品


0
投票

这是正确的解决方案,作者不是我,是他们帮我找到的。

        const product = await this.prismaService.product.findMany({
        where: {
            AND: [
                { options: { some: { title: 'invertor', description: '25' } } },
                { options: { some: { title: 'type', description: 'invertor' } } },
                { options: { some: { title: 'WiFi:', description: 'yes' } } },
            ],
        },
        include: { options: true },
    });
© www.soinside.com 2019 - 2024. All rights reserved.