接口类型
这是 GraphQL 库版本 6 的文档。有关长期支持 (LTS) 版本 5,请参阅 GraphQL 库版本 5 LTS。 |
此页面介绍如何在关系字段上使用和定义接口。
创建接口字段
以下模式定义了一个 Actor
类型,它具有一个 ACTED_IN
关系,类型为 [Production!]!
。Production
是一个接口类型,具有 Movie
和 Series
实现。
interface Production {
title: String!
actors: [Actor!]! @declareRelationship
}
type Movie implements Production @node {
title: String!
actors: [Actor!]! @relationship(type: "ACTED_IN", direction: IN, properties: "ActedIn")
runtime: Int!
}
type Series implements Production @node {
title: String!
actors: [Actor!]! @relationship(type: "ACTED_IN", direction: IN, properties: "ActedIn")
episodes: Int!
}
type ActedIn @relationshipProperties {
role: String!
}
type Actor @node {
name: String!
actedIn: [Production!]! @relationship(type: "ACTED_IN", direction: OUT, properties: "ActedIn")
}
这些类型定义将在本章的其余示例中使用。
查询接口
以下操作将返回每个演员的所有标题以“The ”开头的作品
query GetProductionsStartingWithThe {
actors {
name
actedIn(where: { node: { title_STARTS_WITH: "The " } }) {
title
... on Movie {
runtime
}
... on Series {
episodes
}
}
}
}
以下查询将仅返回每个演员的标题以“The ”开头的电影,方法是通过 typename_IN
对其进行过滤
query GetMoviesStartingWithThe {
actors {
name
actedIn(where: { node: { title_STARTS_WITH: "The ", typename_IN: [Movie] } }) {
title
... on Movie {
runtime
}
}
}
}
使用接口字段创建
下面的突变创建了一个演员和一些他们出演的作品
mutation CreateActorAndProductions {
createActors(
input: [
{
name: "Chris Pratt"
actedIn: {
create: [
{
edge: {
role: "Mario"
}
node: {
Movie: {
title: "Super Mario Bros"
runtime: 90
}
}
}
{
edge: {
role: "Starlord"
}
node: {
Movie: {
title: "Guardians of the Galaxy"
runtime: 122
}
}
}
{
edge: {
role: "Andy"
}
node: {
Series: {
title: "Parks and Recreation"
episodes: 126
}
}
}
]
}
}
]
) {
actors {
name
actedIn {
title
}
}
}
}
嵌套接口操作
对接口的操作是抽象的,直到您指示它们不要抽象。请看以下示例
mutation CreateActorAndProductions {
updateActors(
where: { name_EQ: "Woody Harrelson" }
connect: {
actedIn: {
where: { node: { title_EQ: "Zombieland" } }
connect: { actors: { where: { node: { name_EQ: "Emma Stone" } } } }
}
}
) {
actors {
name
actedIn {
title
}
}
}
}
上面的突变
-
找到任何名为“Woody Harrelson”的
Actor
节点。 -
将“Woody Harrelson”节点连接到标题为“Zombieland”的
Production
节点。 -
将连接的
Production
节点连接到任何名为“Emma Stone”的Actor
节点。