联合类型
这是 GraphQL 库版本 6 的文档。对于长期支持 (LTS) 版本 5,请参阅 GraphQL 库版本 5 LTS。 |
Neo4j GraphQL 库支持在关系字段上使用联合。
例如,考虑以下模式。它定义了一个 User
类型,该类型具有一个 HAS_CONTENT
关系,其类型为 [Content!]!
。Content
的类型为 union
,表示 Blog
或 Post
union Content = Blog | Post
type Blog @node {
title: String
posts: [Post!]! @relationship(type: "HAS_POST", direction: OUT)
}
type Post @node {
content: String
}
type User @node {
name: String
content: [Content!]! @relationship(type: "HAS_CONTENT", direction: OUT)
}
创建联合
要创建示例中介绍的联合,您需要执行此变异
mutation CreateUserAndContent {
createUsers(
input: [
{
name: "Dan"
content: {
Blog: {
create: [
{
node: {
title: "My Cool Blog"
posts: {
create: [
{
node: {
content: "My Cool Post"
}
}
]
}
}
}
]
}
}
}
]
) {
users {
name
}
}
}
查询联合
查询返回哪些联合成员取决于应用于查询的 where
过滤器。以下示例返回所有用户内容,更具体地说,是每个博客的标题
query GetUsersWithBlogs {
users {
name
content {
... on Blog {
title
}
}
}
}
虽然此特定查询只返回博客,但您可以例如使用过滤器来检查博客列表返回时标题是否为空
query GetUsersWithAllContent {
users {
name
content(where: { Blog: { NOT: { title_EQ: null } }}) {
... on Blog {
title
}
}
}
}
这也有助于防止过度获取。