联合类型

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

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

union Content = Blog | Post

type Blog {
    title: String
    posts: [Post!]! @relationship(type: "HAS_POST", direction: OUT)
}

type Post {
    content: String
}

type User {
    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: null } }}) {
            ... on Blog {
                title
            }
        }
    }
}

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