【问题标题】:Hasura - query for tags - null array supposed to return all results, but only returns items with tagsHasura - 查询标签 - 空数组应该返回所有结果,但只返回带有标签的项目
【发布时间】:2020-07-13 23:47:57
【问题描述】:

我有一个问题:

query SearchProductData($tagId: [Int!]) {
  product(where: { productTags: {_or: {tagId: {_in: $tagId}}}}) {
    id
    name
    productTags {
      tag {
        id
        name
      }
    }
  }
}

我传入一个变量

{"tagId": null}

我想取回所有产品,无论它们是否应用了标签。但是会发生什么,它只检索应用了标签的项目,不包括没有标签的项目。

数据库架构是

|- product
   |
   |-- productTags (one to many linking table of productIDs and tagIDs)
       |
       |--- tags

任何想法如何为此用例编写查询?

【问题讨论】:

    标签: hasura


    【解决方案1】:

    这是意料之中的,因为 where 子句如何转换为连接(您可以通过单击 GraphiQL 控制台中的分析来查看生成的 SQL 和执行计划查询分析。)

    我认为不注入 bool 表达式是不可能的。见下文:

    例如

    query Test($expression: product_bool_exp) {
      product(where: $expression) {
        id
        name
        product_tags {
          tag {
            id
            name
          }
        }
      }
    }
    

    带参数

    {
      "expression": {"product_tags": {"tag_id": {"_in": [2]}}}
    }
    

    返回:

    {
      "data": {
        "product": [
          {
            "id": 1,
            "name": "product_A",
            "product_tags": [
              {
                "tag": {
                  "id": 1,
                  "name": "tag_1"
                }
              },
              {
                "tag": {
                  "id": 2,
                  "name": "tag_2"
                }
              }
            ]
          }
        ]
      }
    }
    

    对于使用相同查询的另一种情况(没有传入标签,因此所有产品我们都可以使用这个变量值:

    {
      "expression": null
    }
    

    我们回来了……

    {
      "data": {
        "product": [
          {
            "id": 1,
            "name": "product_A",
            "product_tags": [
              {
                "tag": {
                  "id": 1,
                  "name": "tag_1"
                }
              },
              {
                "tag": {
                  "id": 2,
                  "name": "tag_2"
                }
              }
            ]
          },
          {
            "id": 4,
            "name": "product_D",
            "product_tags": []
          }
        ]
      }
    }
    

    因此,您可以动态构造 where 表达式并将其作为参数传递给查询。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多