PROPERLY SETUP GRAPHQL WITH MULTIPLE VALUES TO ADD

Topic summary

A developer is seeking advice on optimizing their GraphQL implementation for adding metafields to product variants.

Current Approach:

  • Using a foreach loop to process variants individually from webhook payload data
  • Querying products by handle to retrieve variant IDs and creation dates
  • Executing separate mutation requests for each variant to add metafields

The Problem:
The developer acknowledges this loop-based approach is inefficient but functional.

Suggested Solution:
Another user recommends using Shopify’s productVariantsBulkUpdate mutation instead, which allows updating multiple variants in a single API call rather than iterating through them individually.

Status:
The discussion remains open with one potential optimization path identified but not yet implemented.

Summarized with AI on November 18. AI used: claude-sonnet-4-5-20250929.

Hello,

I have a graphql function that add metafields to each variant of the selected products.

My code is working fine BUT i know that doing it in foreach loop is not ideal. Any tips are highly appreciated.

Selected Products are actually coming from a webhook payload. Here’s my sample code.

$handle = $data[‘handle’];

$query = 'query($handle:String!) {
productByHandle(handle:$handle) {
variants(first: 50) {
edges {
node {
id
createdAt
}
}
}
}
}
';
$variables = [
‘handle’ => $handle
];
$payload = [
‘query’ => $query,
‘variables’ => $variables
];
$response = $client->request(‘POST’, $GLOBALS[‘GRAPHQL’] , [‘json’ => $payload]);
$body = json_decode($response->getBody()->getContents(), TRUE);
$variants = $body[‘data’][‘productByHandle’][‘variants’][‘edges’];

foreach($variants as $key => $variant) {
$id = $variant[‘node’][‘id’];
$createdAt = $variant[‘node’][‘createdAt’];

$query2 = ‘mutation($input: ProductVariantInput!) {
productVariantUpdate(input: $input) {
productVariant {
metafield(namespace:“variant”, key: “date_created”) {
value
}
}
}
}’;
$variables2 = [
‘input’ => [
‘id’ => $id,
‘metafields’ => [
‘namespace’ => ‘variant’,
‘key’ => ‘date_created’,
‘value’ => json_encode($createdAt),
‘type’ => ‘single_line_text_field’
]
]
];
$payload2 = [
‘query’ => $query2,
‘variables’ => $variables2
];
$response2 = $client->request(‘POST’, $GLOBALS[‘GRAPHQL’] , [‘json’ => $payload2]);
$body2 = $response2->getBody()->getContents();
print_r($body2);
}

Hey @I_KNOW_NOTHING

Try using the productVariantsBulkUpdate mutation to update them all at once.