【问题标题】:Prisma Reading data - is there a better way to read nested data?Prisma 读取数据 - 有没有更好的方法来读取嵌套数据?
【发布时间】:2021-11-27 02:59:46
【问题描述】:

我目前需要提取大量嵌套数据以格式化为 JavaScript 对象以作为数据发送到图表中,我目前允许嵌套十个深度,但在某些情况下可能会继续进行。

我想知道是否有更好的方法来提取这样的数据,我在文档中看不到任何内容,用于通过关系提取无限或动态嵌套的数据。

这是我目前拥有的例如:

const [result] = await prisma.company.findMany({
  where: {
    users: {
      some: {
        email: {
          contains: session.user.email,
        },
      },
    },
  },
  select: {
    name: true,
    users: true,
    id: true,
    profiles: {
      select: {
        id: true,
        name: true,
        image: true,
        category: {
          select: { name: true },
        },
        children: {
          select: {
            id: true,
            name: true,
            image: true,
            category: {
              select: { name: true },
            },
            children: {
              select: {
                id: true,
                name: true,
                image: true,
                category: {
                  select: { name: true },
                },
                children: {
                  select: {
                    id: true,
                    name: true,
                    image: true,
                    category: {
                      select: { name: true },
                    },
                    children: {
                      select: {
                        id: true,
                        name: true,
                        image: true,
                        category: {
                          select: { name: true },
                        },
                        children: {
                          select: {
                            id: true,
                            name: true,
                            image: true,
                            category: {
                              select: { name: true },
                            },
                          },
                        },
                      },
                    },
                  },
                },
              },
            },
          },
        },
      },
    },
  },
});

【问题讨论】:

    标签: javascript database prisma


    【解决方案1】:

    您是否考虑过使用include 语句代替select?它会自动获取所有非关系字段,因此您只需手动指定关系字段。 prisma 文档中的The nested reads section 也包含很多这方面的示例。

    一般来说,如果您不需要精细控制从查询中返回模型的哪些字段,include 是您的最佳选择。

    Please check out my answer to a very similar question。我认为您可能会发现该解决方案与您的用例相关。

    【讨论】:

    • 嗯,我之前将它作为包含,但这并没有包括它们的嵌套关系,除非我做错了什么。我会再试一次。并且给了我太多的图表数据 - 可能不是问题,但我觉得它用更少的数据更干净。
    • 您可以嵌套include 任意多个级别,因此您可以嵌套5-6 层,类似于您在此处使用select 所做的操作。但是它不那么冗长,因为您只需要指定relation 字段,数据字段会自动返回。尽管从查询中返回更少的数据:这是您必须做出的权衡。 include 将返回更多数据,但代码会更简洁,select 则相反。不幸的是,你不能两者兼得。
    猜你喜欢
    • 2019-10-17
    • 1970-01-01
    • 2010-11-11
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    相关资源
    最近更新 更多