首页 > 解决方案 > 如何对 Hasura 中的 ARRAY 字段类型运行 GraphQL 过滤器查询?

问题描述

我正在尝试对数组字段类型运行 GraphQL 过滤器查询,例如在文本 ARRAY 字段类型上。

在以下示例场景中:

创建表

CREATE TABLE Employee (
    firstName       text,
    lastName        text,    
    tags            text[]
);

我们可以通过以下方式之一过滤文本数组字段:

在 ARRAY 类型上使用 CONDITION SELECT STATEMENT

SELECT * FROM Employee WHERE tags @> ARRAY['teamplayer']::varchar[]

这在 PostGres 和 Postgraphile 中隐式有效。

在 Postgraphile GraphQL 上,我们可以查询上表如下:

询问

{
  allEmployees(filter: {tags: {contains: "teamplayer"}}) {
    nodes {
      firstName
      lastName
      tags
    }
  }
}

结果将是:

回复

  {
  "data": {
    "allEmployees": {
      "nodes": [
         {
             firstName: 'Russell'
             lastName: 'Dodds'
             tags: ['teamplayer', 'punctual']
         },
         {
             firstName: 'Emma'
             lastName: 'Samsin'
             tags: ['teamplayer']
         }
      ]
    }
  }
}

有人可以给我一些关于如何在 Hasura 中的 ARRAY 字段类型上获得类似结果的参考或建议吗?

标签: graphqlhasurapostgraphile

解决方案


我认为您不能直接在 Hasura 控制台中使用数组。你应该jsonb改用。它更合适,因为您可以使用_append, _prepend, _delete_key...

但似乎您可以Array与 hasura 一起使用。如果您的架构来自外部服务,则数组的输入应该是文字。对于类型tags[]的列,输入值必须是字符串,如:"{teamplayer,punctual}"。这就是Array 在 postgres 中的工作方式。

所以你的突变将是:

mutation {
  insert_table(objects:{
    tags: "{teamplayer,punctual}"
  }) {
    returning {
      tags
    }
  }
}

推荐阅读