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

GraphQL查询过滤语法及示例求助:基于现有后端实现

GraphQL过滤查询使用指南及扩展示例

问题背景

已能通过Postman执行基础GraphQL查询:

{
  tblprojects {
    id
    name
  }
}

但尝试用name参数过滤时触发错误:

{
  tblprojects(name:"Test") {
    id
    name
  }
}

错误信息:

"message": "Unknown argument \"name\" on field \"tblprojects\" of type \"Query\".",

后端PHP代码如下:

$queryFields = [];
foreach ($tables as $table) {
    $queryFields[$table] = [
        'type' => Type::listOf(new ObjectType([
            'name' => ucfirst($table),
            'fields' => function() use ($table) {
                return $this->getFieldsFromTable($table);
            },
        ])),
        'args' => [
            'id_in' => [
                'type' => Type::listOf(Type::int()), // Allow filtering by an array of integers
            ],
        ],
        'resolve' => function($root, $args) use ($table) {
            if (isset($args['id_in']) && !empty($args['id_in'])) {
                // Apply filtering if 'id_in' argument is passed
                $this->db->where_in('id', $args['id_in']);
            }
            return $this->db->get($table)->result();
        },
    ];
}

一、正确使用id_in参数

后端仅定义了id_in作为过滤参数,用于匹配id在指定数组中的记录,查询示例:

{
  tblprojects(id_in: [1, 3, 5]) {
    id
    name
  }
}

该查询会返回所有id为1、3、5的tblprojects记录,对应后端的where_in逻辑。


二、扩展更多过滤操作符的实现及测试示例

如果需要更多过滤能力,需修改后端代码添加对应参数,以下是常见操作符的实现及查询示例:

1. 单ID精确匹配(id)

后端修改

在args数组中添加:

'id' => [
    'type' => Type::int(),
],

在resolve函数中添加条件判断:

if (isset($args['id'])) {
    $this->db->where('id', $args['id']);
}

查询示例

{
  tblprojects(id: 2) {
    id
    name
  }
}

2. 名称模糊匹配(name_like)

后端修改

在args数组中添加:

'name_like' => [
    'type' => Type::string(),
],

在resolve函数中添加:

if (isset($args['name_like'])) {
    $this->db->like('name', $args['name_like']);
}

查询示例(匹配名称包含"Test"的项目)

{
  tblprojects(name_like: "Test") {
    id
    name
  }
}

3. 名称精确匹配(name)

后端修改

在args数组中添加:

'name' => [
    'type' => Type::string(),
],

在resolve函数中添加:

if (isset($args['name'])) {
    $this->db->where('name', $args['name']);
}

查询示例

{
  tblprojects(name: "Test Project") {
    id
    name
  }
}

4. 多条件组合查询

当后端同时支持多个过滤参数时,可组合使用。比如同时用id_in和name_like:

{
  tblprojects(id_in: [1, 4, 6], name_like: "Test") {
    id
    name
  }
}

该查询会返回id在[1,4,6]范围内且名称包含"Test"的项目。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 22:03:11