联合类型

这是 GraphQL 库版本 7 的文档。对于长期支持 (LTS) 版本 5,请参阅 GraphQL 库版本 5 LTS

Neo4j GraphQL 库支持在关系字段上使用联合类型。

举例来说,考虑以下模式。它定义了一个 User 类型,该类型有一个 HAS_CONTENT 关系,类型为 [Content!]!Content 的类型是 union,表示 BlogPost

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
            }
        }
    }
}

这也有助于防止过度获取数据。

© . All rights reserved.