【问题标题】:Using multiple mutations in one call在一次调用中使用多个突变
【发布时间】:2026-01-18 15:35:01
【问题描述】:

我已经编写了我的第一个使用 GraphQL 的脚本(仍然是一个学习曲线)

目前我正在使用 GraphQL 进行 3 次调用, 首先是产品查找, 其次是价格更新, 第三是库存更新。

为了减少对终点的调用次数,我想合并价格更新和库存,但是我的运气为 0,我不知道它的格式是否错误。

这是我的 GraphQL 代码(我正在使用 Postman 来帮助确保架构正确,然后再将其带到 PHP 中)

mutation  productVariantUpdate($input: ProductVariantInput!) {
  productVariantUpdate(input: $input) {
    product {
      id
    }
    productVariant {
      id
      price
    }
    userErrors {
      field
      message
    }}

 second:  inventoryActivate($inventoryItemId: ID!, $locationId: ID!, $available: Int) {
  inventoryActivate(inventoryItemId: $inventoryItemId, locationId: $locationId, available: $available) {
    inventoryLevel {
      id
      available
    }
    userErrors {
      field
      message
    }
  }
}
}
    

变量:

{
"inventoryItemId": "gid://shopify/InventoryItem/XXXXXXXXXXX",
"locationId": "gid://shopify/Location/XXXXXXXXXX",
"available": 11 ,
  "input": {
    "id": "gid://shopify/ProductVariant/XXXXXXXXX",
    "price": 55
  }
}

我不断收到错误:

{
    "errors": [
        {
            "message": "Parse error on \"$\" (VAR_SIGN) at [29, 29]",
            "locations": [
                {
                    "line": 29,
                    "column": 29
                }
            ]
        }
    ]
}

【问题讨论】:

    标签: graphql shopify


    【解决方案1】:

    您要解决此问题的方法是在 mutation 的根目录中指定所有参数,就像您为 ProductVariantInput 所做的那样:

    mutation batchProductUpdates(
      $input: ProductVariantInput!
      $inventoryItemId: ID!
      $locationId: ID!
      $available: Int
    ) {
      
      productVariantUpdate(input: $input) {
        product { id }
        productVariant { id price }
        ...
      }
      
      inventoryActivate(
        inventoryItemId: $inventoryItemId
        locationId: $locationId
        available: $available
      ) {
        inventoryLevel { id available }
        ...
      }
    
    }
    

    这是一个示例,如果您在 JavaScript 中使用 fetch,这将如何工作:

    fetch("https://example.com/graphql", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        query: `
          mutation MyMutation($firstId: Int, $secondId: Int) {
            m1: ToggleLike(id: $firstId) {
              id
            }
            m2: ToggleLike(id: $secondId) {
              id
            }
          }
        `,
        variables: {
          firstId: 1,
          secondId: 2
        }
      })
    })
    

    希望这会有所帮助。

    【讨论】:

    • 非常感谢您,解释了我收到的各种格式的其他消息。也感谢这个例子,现在更有意义了。
    • 感谢您的回答,您可以使用第一次调用返回的值并在第二次调用中使用它吗?
    • @BradyEdgar 您必须进行 2 次单独的调用,因此如果您使用 fetch,您可以在 .then 回调中进行第二次调用,并使用第一次调用的返回值。
    • @goto1 好的,谢谢你的更新,我现在正在这样做,我只是希望我能把它挤进一个电话里。谢谢