您可以使用我们所谓的嵌套突变来实现这一点。
首先,让我们看看如何在 GraphiQL 游乐场上做到这一点:
mutation createNestedCompany {
createCompany(
owner: {
name: "Mickey"
email: "[email protected] /cdn-cgi/l/email-protection"
}
addresses: [{
street: "A street"
city: "A city"
country: "A country"
contacts: [{
name: "Mickey"
email: "[email protected] /cdn-cgi/l/email-protection"
phone: "+1 23456789"
}]
}, {
street: "B street"
city: "B city"
country: "B country"
contacts: [{
name: "Minney"
email: "[email protected] /cdn-cgi/l/email-protection"
phone: "+9 87654321"
}]
}]
) {
id
owner {
id
}
addresses {
id
contacts {
id
}
}
}
}
请注意,createCompany
突变有对象参数owner
和列表对象参数addresses
. addresses
有一个嵌套的contacts
列表对象参数。
使用 Apollo Client,我们使用 GraphQL 变量指定输入参数,所以让我们看看在这种情况下它是什么样的:
const createNestedCompany = gql`
mutation createNestedCompany(
$owner: CompanyownerUser
$addresses: [CompanyaddressesAddress!]
) {
createCompany(
owner: $owner
addresses: $addresses
) {
id
owner {
id
}
addresses {
id
contacts {
id
}
}
}
}
`
当使用 Apollo 调用突变时,我们现在必须将变量指定为对象:
const variables = {
owner: {
name: "Mickey"
email: "[email protected] /cdn-cgi/l/email-protection"
},
addresses: [{
street: "A street"
city: "A city"
country: "A country"
contacts: [{
name: "Mickey"
email: "[email protected] /cdn-cgi/l/email-protection"
phone: "+1 23456789"
}]
}, {
street: "A street"
city: "A city"
country: "A country"
contacts: [{
name: "Minney"
email: "[email protected] /cdn-cgi/l/email-protection"
phone: "+9 87654321"
}]
}]
}
并用变量调用突变:
this.props.createNestedCompany({ variables })
.then((response) => {
console.log('Company, owner and addresses plus contacts created');
}).catch((e) => {
console.error(e)
})
变量类型CompanyownerUser
and [CompanyaddressesAddress!]
取决于以下的组合多重性(对一;对多),相关型号 (Company
and User
; Company
and Address
) and 相关领域 (owner
; addresses
)。当您导航到 GraphQL Playground 文档时,您可以找到所有类型名称createCompany
突变。