graphql - GraphQL - 如何在查询多个突变期间检索先前突变的 id
问题描述
我想在同一个查询中运行多个突变。
在下面的示例中,我创建了一个订单,然后创建了一个产品记录,涉及先前创建的。
我必须有2个突变。
首先,我插入一个订单。在输出中,我检索了 idorder。
然后,我插入一个产品。这个产品
mutation {
createOrder(input: {
order: {
ordername: "My order"
}
}) {
order {
idorder
ordername
}
},
createProduct(input: {
product: {
quantity: 3
idrefproduct: 25 # link to refProduct
idorder: XXXX # how can i retrieve idorder from output of createOrder above ?
}
}) {
product {
idproduct
}
}
}
SQL结构的真实示例:
user(iduser, othersFields);
scenarios(idscenario, iduser, name, otherFields);
cultA(idcultA, idscenario, ...); // this table need of idscenario field
cultB(idcultB, idscenario, ...); // this table need of idscenario field
cultC(idcultC, idscenario, ...); // this table need of idscenario field
如何从上面的 createOrder 输出中检索 idorder?
有可能的 ?
如果我忘记了一些信息,请不要犹豫。
提前致谢。
编辑:
- 使用 PostGraphile,插件“postgraphile-plugin-nested-mutations”或“自定义突变”(带有 PL PGSQL 功能)
- 在没有 PostGraphile 的情况下,作为 @xadm 示例的解析器允许这种特定的嵌套突变。
解决方案
恕我直言,您可以搜索“嵌套突变”-此处未描述,您可以轻松找到示例/教程。
建议的数据库结构(n 对 n 关系):
order{orderID,lines[{orderLineID}] } >
order_line{orderLineID, productID, anount, price} >
product {productID}
...在嵌套突变中创建(以相反的顺序 product>order_line>order)
产品不需要orderID
,但当您要求时 [在产品解析器中]
query product(id) {
id
orderedRecently {
orderID
date
price
}
}
orderLines
...您可以简单地从表中获取它(或相当多的数组)orders
[使用简单的 SQL 查询-price
将从哪里读取orderLines
]
orderedRecently
解析器可以id
从父对象获取产品(通常是第一个参数)
当然,您可以(并且应该)将数据作为order
和orderLine
类型返回(单独缓存,规范化):
query product($id: ID!) {
product(id: $id) {
id
orderedRecently {
id
date
orderLine {
id
amount
price
}
}
}
}
其中类型orderedRecently: [Order!]
- 数组可以为空,尚未排序
更新
我稍微误解了你的要求(命名约定)......你已经有了正确的数据库结构。突变可以用复杂的数据/输入“喂养”:
mutation {
createOrder(input: {
order: {
ordername: "My order"
products: [
{
quantity: 3
idrefproduct: 25
},
{
quantity: 5
idrefproduct: 28
}
]
}
}) {
order {
id
ordername
products {
id
idrefproduct
quantity
}
}
}
}
你product
是我的orderLine
,idrefproduct
是的product
。
createOrder
创建/插入order
,然后将其id
用于创建产品记录(order.id
和idrefproduct
)quantity
。解析器只能返回订单id
或结构化数据(如上)。
推荐阅读
- c++ - 理解 std::fmod 和 std::remainder
- activemq - 我在哪里可以找到 ActiveMQ Real Time 的构建?
- python - 字典键的交集是什么
- lstm - CuDNNLSTM:UnknownError:找不到 dnn 实现
- linux - 如何为安装在远程机器上的 docker 创建用户名和密码?
- ruby-on-rails - ActiveRecord::StatementInvalid: PG::UndefinedTable: 错误: 缺少表“位置”的 FROM 子句条目
- javascript - 无服务器函数中的数据库连接缓存代码仅执行一次
- eslint - 有没有更好的方法来抑制赛普拉斯开玩笑测试顶部关于“三斜杠指令”的 ESLint 错误?
- c# - Dot Net Core 中的“IWebHost”和“IWebHostBuilder”有什么不同?
- nginx-reverse-proxy - NGINX反向代理两个不同的服务器作为后端