【问题标题】:How to query nested data in a REST API built with Prisma如何在使用 Prisma 构建的 REST API 中查询嵌套数据
【发布时间】:2019-11-23 10:08:55
【问题描述】:

我正在使用ExpressPrisma 构建一个REST API。我有一个Prisma 数据模型,如下所示

type User {
  id: ID! @id
  email: String! @unique
  name: String
  posts: [Post!]! @relation(link: INLINE)
}

type Post {
  id: ID! @id
  createdAt: DateTime! @createdAt
  updatedAt: DateTime! @updatedAt
  published: Boolean! @default(value: false)
  title: String!
  content: String
  author: User!
}

现在,如果我像这样查询数据

const posts = await prisma.users()

它只返回帖子。

[
  {
    "id": "cjo5vwaaq6e7p0a42qpoz3aj3",
    "email": "ada@prisma.io",
    "name": "Ada"
  }
]

但我也想在用户对象中获取用户的所有帖子。

[
    {
      "id": "cjo5vwaaq6e7p0a42qpoz3aj3",
      "email": "ada@prisma.io",
      "name": "Ada", 
      "posts": [
         {
            "title": "This is title"
         }
       ]
    }
]

我该怎么做?我是Prisma 的新手。我知道我不必使用Prisma 来构建 REST API,但我必须这样做。 但是我没有找到与 REST API 一起使用的 Prisma 的任何好的文档。

【问题讨论】:

    标签: node.js mongodb rest prisma


    【解决方案1】:

    要查询关系数据,您需要使用片段或 prisma fluent API。正如您已经发现的那样,prisma 客户端只返回标量字段而没有关系。您的帖子是一种关系。

    每当使用 Prisma 客户端查询数据库记录时,所有 获取该记录的标量字段。这是真的,无论是否 查询单个记录或记录列表。

    见:https://www.prisma.io/docs/prisma-client/basic-data-access/reading-data-JAVASCRIPT-rsc2

    对于单个查询(例如获取单个用户),您可以使用 prisma fluent API。因此,在您的情况下,您可以编写某个用户的帖子:

    const posts = await prisma.user({ where: { email: 'test@test.de' }})).posts()
    

    见:https://www.prisma.io/docs/prisma-client/basic-data-access/reading-data-JAVASCRIPT-rsc2/#relations

    这仅适用于单个记录,不适用于列表。要检索所有记录的数据,您需要使用片段。例如。要在用户数据旁边获取相关的帖子数据,您可以编写如下内容:

    const fragment = `
      fragment UserWithPosts on User {
        id
        name
        email
        posts {
          id
          title
        }
      }
    `
    
    const userWithPosts = await prisma.users().$fragment(fragment)
    

    见:https://www.prisma.io/docs/prisma-client/basic-data-access/reading-data-JAVASCRIPT-rsc2/#selecting-fields

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-01
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 2020-10-17
      • 2018-05-18
      • 2019-03-23
      相关资源
      最近更新 更多