您可以使用我们所谓的嵌套突变来实现这一点。首先,让我们看看我们如何在 GraphiQL 操场上做到这一点:
mutation createNestedCompany {
createCompany(
owner: {
name: "Mickey"
email: "mickey@mouse.com"
}
addresses: [{
street: "A street"
city: "A city"
country: "A country"
contacts: [{
name: "Mickey"
email: "mickey@mouse.com"
phone: "+1 23456789"
}]
}, {
street: "B street"
city: "B city"
country: "B country"
contacts: [{
name: "Minney"
email: "minney@mouse.com"
phone: "+9 87654321"
}]
}]
) {
id
owner {
id
}
addresses {
id
contacts {
id
}
}
}
}
请注意,createCompany
突变具有对象参数owner
和列表对象参数addresses
。addresses
有一个嵌套contacts
列表对象参数。
使用 Apollo 客户端,我们使用 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: "mickey@mouse.com"
},
addresses: [{
street: "A street"
city: "A city"
country: "A country"
contacts: [{
name: "Mickey"
email: "mickey@mouse.com"
phone: "+1 23456789"
}]
}, {
street: "A street"
city: "A city"
country: "A country"
contacts: [{
name: "Minney"
email: "minney@mouse.com"
phone: "+9 87654321"
}]
}]
}
并使用变量调用突变:
this.props.createNestedCompany({ variables })
.then((response) => {
console.log('Company, owner and addresses plus contacts created');
}).catch((e) => {
console.error(e)
})
变量类型CompanyownerUser
和[CompanyaddressesAddress!]
取决于多重性(一对一;对多)、相关模型(Company
和User
;Company
和Address
)和相关字段(owner
;addresses
)的组合。当您导航到createCompany
突变时,您可以在 GraphiQL 游乐场文档中找到所有类型名称。