【问题标题】:How do I make a Hasura data API query to fetch rows based on the length of the their array relationship's value?如何进行 Hasura 数据 API 查询以根据数组关系值的长度获取行?
【发布时间】:2023-03-31 10:14:01
【问题描述】:

参考https://hasura.io/hub/project/hasura/hello-world/data-apis 中提到的默认示例架构,即以下两个表:

1) 作者:id、姓名

2) 文章:id、标题、内容、评级、author_id

其中article:author_idauthor:id 具有数组关系。

如何进行查询以选择至少写过一篇文章的作者?基本上,类似select author where len(author.articles) > 0

【问题讨论】:

    标签: hasura


    【解决方案1】:

    TL;DR:

    目前没有可以在 Hasura 数据 API 语法中使用的 length 函数。解决方法 1) 过滤保证每一行都为真的属性。喜欢id > 0。 2) 构建视图并在视图上公开 API。


    选项 1:

    使用“始终为真”属性作为过滤器。

    {
        "type": "select",
        "args": {
            "table": "author",
            "columns": [
                "*"
            ],
            "where": {
                "articles": {
                    "id": {
                        "$gt": "0"
                    }
                }
            }
        }
    }
    

    这读作:select all authors where ANY article has id > 0 这是因为 id 是一个自动递增的 int。

    选项 2:

    创建一个视图,然后在其上公开数据 API。

    前往 API 控制台中的运行 SQL 窗口并运行迁移:

    CREATE VIEW author_article_count as (
      SELECT au.*, ar.no_articles 
      FROM 
        author au, 
        (SELECT author_id, COUNT(*) no_articles FROM article GROUP BY author_id) ar
      WHERE
        au.id = ar.author_id)
    

    确保将其标记为迁移(RunSQL 窗口下方的复选框),以便将其添加到迁移文件夹中。 现在,通过点击 API 控制台架构页面上的“跟踪表”,将数据 API 添加到视图。

    现在您可以使用 no_articles 作为长度属性进行选择查询:

    {
        "type": "select",
        "args": {
            "table": "author_article_count",
            "columns": [
                "*"
            ],
            "where": {
                "no_articles": {
                    "$gt": "0"
                }
            }
        }
    }
    

    【讨论】:

    • 谢谢!使用选项#2,因为它适用于任意len
    猜你喜欢
    • 2018-10-24
    • 2019-03-22
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    相关资源
    最近更新 更多