【问题标题】:Do I have to create a new type to define array of objects in GraphQL schemas?我是否必须创建一个新类型来定义 GraphQL 模式中的对象数组?
【发布时间】:2020-01-02 05:17:16
【问题描述】:

我正在尝试复制我过去构建的 REST API,其中一个让我思考的部分是我的一个表是否有一组对象。例如,我有一个名为 Profile 的表,它包含数组 Experience 和 Education,它们严格位于 Profile 下,但也有自己的字段,但没有自己的表。

当我在 GraphQL 中添加字段时,我遇到了这个问题在体验/教育部分之前。我不确定这是否是正确的方法,或者是否有更好的方法。下面是我最终使用的一个 sn-p……查看管理页面,有为 Profile、Experience 和 Education 创建的表,这是预期的。但是有没有办法只拥有 Profile 并完成类似的事情?或者这更像是 GraphQL 的一种生活方式?

type Profile {
    id: ID! @id
    handle: String!
    company: String
    website: String
    location: String
    status: String!
    githubUsername: String
    experience: [Experience!] @relation(link: INLINE)
    education: [Education!] @relation(link: INLINE)
}

type Experience {
  id: ID! @id
  title: String!
  company: String!
}

type Education {
  id: ID! @id
  title: String!
  company: String!
}

【问题讨论】:

  • 这个问题确实是 Prisma 特有的。 GraphQL 本身并不关心存储层。

标签: graphql prisma prisma-graphql


【解决方案1】:

在 Prisma 中,您可以使用 embedded types。您将删除 @relation 指令并将 @embedded 指令添加到您要嵌入的类型:

type Profile {
    id: ID! @id
    handle: String!
    company: String
    website: String
    location: String
    status: String!
    githubUsername: String
    experience: [Experience!]
    education: [Education!]
}

type Experience @embedded {
  title: String!
  company: String!
}

type Education @embedded {
  title: String!
  company: String!
}

但是,这只有在您将 MongoDB 用于您的数据库并且在使用嵌入式类型时文档中列出了一些特定限制时才有可能。

【讨论】:

  • 哦,这正是我要找的!谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-04-14
  • 1970-01-01
  • 2018-02-23
  • 1970-01-01
  • 2021-09-22
  • 2015-09-14
  • 2013-03-04
  • 1970-01-01
相关资源
最近更新 更多