Hasura 中的一个计算字段 returns 一个整数数组

A computed field in Hasura that returns an array of integer

问题

我正在尝试添加 return 是一个整数数组的计算字段。 Hasura 目前支持 return 类型的 SETOF <table-name>BASE 类型。我尝试 returning 一个 integer[] 但它失败了(它不是 BASE 类型)。有解决办法吗?

这是我试过的

我有两个table:课程和小测验,一门课程有很多小测验,每个小测验都有一个名为difficulty的整数字段。 我想在课程 table 中添加一个计算字段,列出相关测验的不同难度。

使用 SQL 我们可以创建一个数组,用这个查询生成这个列表:

SELECT array(SELECT DISTINCT difficulty FROM quizzes
  WHERE course_id = 1 ORDER BY difficulty ASC);

所以我创建了一个函数,该函数 return 是该查询的结果,并将其作为计算字段添加到课程 table

CREATE OR REPLACE FUNCTION courses_quiz_difficulties(course_row courses)
RETURNS integer[] AS $$
  SELECT array(SELECT DISTINCT difficulty FROM quizzes
  WHERE course_id = course_row.id ORDER BY difficulty ASC);
$$
LANGUAGE SQL STABLE;

当我尝试添加计算字段时,出现错误,因为 int 数组不是 BASE 类型。

in table "courses": in computed field "quiz_difficulties": the computed field "quiz_difficulties" cannot be added to table "courses" because the function "courses_quiz_difficulties" returning type _int4 is not a BASE type

是否有解决方法可以使其与 Hasura 一起使用?

这里是对应的文档:

https://hasura.io/docs/1.0/graphql/manual/schema/computed-fields.html#supported-sql-functions

一个简单的视图给了我想要的结果:

CREATE VIEW course_quiz_difficulties AS        
    SELECT 
        course_id, 
        array_agg(DISTINCT difficulty ORDER BY difficulty) as quiz_difficulties
    FROM quizzes GROUP BY course_id

之后我们可以手动添加课程和新视图之间的关系: courses . id → course_quiz_difficulties . course_id

Hasura 允许我们从 courses:

查询 quiz_difficulties
query MyCourseQuizDifficulties {
  courses(limit: 1) {
    id
    quiz_difficulties {
      quiz_difficulties
    }
  }
}

我们得到这个结果:

{
  "data": {
    "courses": [
      {
        "id": 1,
        "quiz_difficulties": {
          "quiz_difficulties": [
            1,
            2
          ]
        }
      }
    ]
  }
}