You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中使用变量创建动态GraphQL查询?

改造方案

核心修改思路

把固定的GraphQL查询改为支持变量传递的模板,同时统一处理单个数字/数字数组的输入,按需实现循环请求或批量查询。


方案1:循环处理单个productType(逐个请求)

适合需要单独获取每个类型数据的场景,不管输入是单个数字还是数组,统一转成数组后循环遍历:

// 目标productType集合:单个值用数组包裹,多值直接传数组
$targetProductTypes = [2, 3, 5]; // 示例:单个值可写为 [4]

// 带变量的GraphQL查询模板
$query = <<<'GRAPHQL'
query GetMainProducts($productType: Int!) {
  mainProducts(where:{productType:{eq:$productType}}) {
    name
    productID
  }
}
GRAPHQL;

// 循环处理每个productType
foreach ($targetProductTypes as $type) {
    // 构造当前请求的变量参数
    $variables = ['productType' => $type];
    
    // 组装GraphQL请求体
    $json = json_encode([
        'query' => $query,
        'variables' => $variables
    ]);

    // 初始化CURL并设置参数
    $chObj = curl_init();
    curl_setopt($chObj, CURLOPT_URL, 'https://whateverurlitis.com');
    curl_setopt($chObj, CURLOPT_RETURNTRANSFER, true);    
    curl_setopt($chObj, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($chObj, CURLOPT_HEADER, true);
    curl_setopt($chObj, CURLOPT_VERBOSE, true);
    curl_setopt($chObj, CURLOPT_POSTFIELDS, $json);
    curl_setopt($chObj, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json;charset=utf-8',
        'Authorization: bearer '.MYTOKEN 
    ]); 

    // 执行请求并输出结果
    $response = curl_exec($chObj);
    echo "处理productType: {$type} 的响应:\n";
    echo $response . "\n\n";

    // 释放CURL资源
    curl_close($chObj);
}

方案2:批量查询多个productType(一次请求)

如果需要一次性获取所有目标类型的数据,改用GraphQL的in条件匹配数组变量:

// 目标productType:单个值或数组都兼容
$targetProductTypes = [2, 3, 5]; // 单个值可写为 [4]

// 支持数组变量的GraphQL查询
$query = <<<'GRAPHQL'
query GetMainProducts($productTypes: [Int!]!) {
  mainProducts(where:{productType:{in:$productTypes}}) {
    name
    productID
  }
}
GRAPHQL;

// 构造变量参数
$variables = ['productTypes' => $targetProductTypes];

// 组装请求体
$json = json_encode([
    'query' => $query,
    'variables' => $variables
]);

// CURL请求逻辑和之前一致
$chObj = curl_init();
curl_setopt($chObj, CURLOPT_URL, 'https://whateverurlitis.com');
curl_setopt($chObj, CURLOPT_RETURNTRANSFER, true);    
curl_setopt($chObj, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($chObj, CURLOPT_HEADER, true);
curl_setopt($chObj, CURLOPT_VERBOSE, true);
curl_setopt($chObj, CURLOPT_POSTFIELDS, $json);
curl_setopt($chObj, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json;charset=utf-8',
    'Authorization: bearer '.MYTOKEN 
]); 

$response = curl_exec($chObj);
echo $response;
curl_close($chObj);

关键修改点

  1. GraphQL查询模板化:用$变量名替换固定值,定义变量类型(Int!表示非空整数,[Int!]!表示非空整数数组)
  2. 输入统一处理:单个数字也用数组包裹,避免分支判断
  3. 变量传递规范:确保请求体中variables的键名和GraphQL定义的变量名完全一致
  4. 资源释放:循环场景下每次请求后关闭CURL资源,避免内存泄漏

内容的提问来源于stack exchange,提问作者Vincensiu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:48:11