gpt4 book ai didi

graphql - 如何在一个突变中创建嵌套节点?

转载 作者:行者123 更新时间:2023-12-04 16:38:42 24 4
gpt4 key购买 nike

嗨,我正在尝试在我的 https://www.graph.cool/ 上写入数据db 有一个突变。
我的项目是一个 React 网络应用程序,我使用 Apollo 作为 graphql 客户端和 graphql-tag npm 包作为模板文字解析器。

问题是我不知道如何使用嵌套数据为正确的突变安排 gql 模板字符串。
我的架构看起来像这样,例如注意“公司”类型的“地址”字段是“地址”对象类型的数组。

type Company {
name: String!
website: String
Owner: User
Addresses: [Addresses]
}

type User {
name: String!
email: String
}

type Address {
street: String!
city: String!
country: String
contacts: [Contact]
}

type Contact {
name: String
email: String
phone: String
}

例如,我想在一个突变中同时创建一个新公司、它的新所有者和多个地址。对于地址,我还需要创建一个新联系人。

最佳答案

您可以使用我们所谓的嵌套突变来实现这一点。
首先,让我们看看如何从 GraphiQL playground 做到这一点:

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 和列表对象参数 addressesaddresses 有一个嵌套的 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: "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!]取决于 的组合的多样性(以酮;对多), 相关模型( CompanyUser; CompanyAddress)和 的相关领域( owner; addresses) .当您导航到 createCompany 突变时,您可以在 GraphiQL 游乐场文档中找到所有类型名称。

关于graphql - 如何在一个突变中创建嵌套节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42133424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com