【问题标题】:How do I use "AND" operator with multiple query parameters in nested relation when querying in Prisma?在 Prisma 中查询时,如何在嵌套关系中使用带有多个查询参数的“AND”运算符?
【发布时间】:2021-09-20 10:00:52
【问题描述】:

这是我第一次尝试 prisma 并且卡住了。所以我有“产品”和“过滤器”模型。

我希望以下查询起作用。这个想法是,我想获取具有动态匹配查询参数(名称和值)的产品。产品查询参数动态来自前端。

const products = await prisma.product.findMany({
        where: {
          categoryName,
          subCategoryName,
          filters: {
            some: {
              AND: [
                {
                  name: "RAM",
                  value: "32GB",
                },
                {
                  name: "Storage",
                  value: "1TB",
                },
              ],
            },
          },
        },
        include: {
          images: true,
        },
      });

如果只有一个参数,比如

{
  name:"RAM",
  value:"32GB"
}

查询返回适当的产品,但如果有多个查询参数(如上面的原始代码),则返回空数组。

我的产品架构看起来像这样,经过简化,

  name                      String      
  filters                   Filter[]

我的过滤器架构看起来像这样,简化

  name                      String      
  value                     String?
  product                   Product?    @relation(fields: [productId], references:[id])
  productId                 Int?

非常感谢

【问题讨论】:

    标签: node.js postgresql prisma prisma2


    【解决方案1】:

    我在这里找到了解决方案 https://github.com/prisma/prisma/discussions/8216#discussioncomment-992302

    显然应该是这样的。

    await prisma.product.findMany({
          where: {
            AND: [
              { price: 21.99 },
              { filters: { some: { name: 'ram', value: '8GB' } } },
              { filters: { some: { name: 'storage', value: '256GB' } } },
            ],
          },
    })
    

    【讨论】:

    • 您介意告诉我在使用 where 查询时如何避免返回重复项吗?假设一条数据匹配两个过滤器,在这种情况下它会返回两次。
    • @Dipzera 尝试使用 findFirst 可能吗?
    猜你喜欢
    • 2016-08-23
    • 1970-01-01
    • 2019-07-10
    • 2019-03-23
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多