首页 > 解决方案 > 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?

有可能的 ?

如果我忘记了一些信息,请不要犹豫。

提前致谢。

编辑

标签: graphqlpostgraphile

解决方案


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

建议的数据库结构(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从父对象获取产品(通常是第一个参数)

当然,您可以(并且应该)将数据作为orderorderLine类型返回(单独缓存,规范化):

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是我的orderLineidrefproduct是的product

createOrder创建/插入order,然后将其id用于创建产品记录(order.ididrefproductquantity。解析器只能返回订单id或结构化数据(如上)。


推荐阅读