GraphQL-在查询多个突变期间如何检索先前突变的id

时间:2020-04-17 10:02:07

标签: graphql postgraphile

我想在同一查询中运行多个变异。

在下面的示例中,我创建了一个订单,并在创建了产品记录后,涉及先前创建的记录。

我必须有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为例的解析器允许这种特殊的嵌套变异。

1 个答案:

答案 0 :(得分:0)

恕我直言,您可以搜索“嵌套突变”-此处未描述,您可以轻松找到示例/教程。

建议的数据库结构(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
  }
}

... [使用简单的SQL查询,您可以简单地从orderLinesorders表中获取(或相当多的数组),其中将从{{1 }}]

price解析器可以从父对象(通常是第一个参数)获取乘积orderLines

您当然可以(并且应该)以orderedRecentlyid类型返回数据(要分别缓存,进行规范化):

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 } } } } productorderLine

idrefproduct创建/插入product,然后使用其createOrder创建产品记录(orderidorder.id)。解析程序只能返回订单idrefproduct或结构化数据(如上所述)。