Skip to content
Advertisement

Hasura GraphQL query : where clause with value from related entity

I recently started using GraphQL through a Hasura layer on top of a PostgreSQL DB. I am having troubles implementing a basic query.

Here are my entities :

article :

  • articleId
  • content
  • publishedDate
  • categoryId

category :

  • categoryId
  • name
  • createdDate

What I am trying to achieve, in English, is the following : get the articles that were published in the first 3 days following the creation of their related category.

In pseudo-SQL, I would do something similar to this :

SELECT Article.content, Category.name
FROM Article
INNER JOIN Category ON Article.categoryId = Category.categoryId
WHERE Article.publishedDate < Category.createdDate + 3 days

Now as a GraphQL query, I tried something similar to this :

query MyQuery {
    articles(where: {publishedDate: {_lt: category.createdDate + 3 days}}) {
        content
        category {
            name
        }
    }
}

Unfortunately, it does not recognise the “category.createdDate” in the where clause. I tried multiple variations, including aliases, with no success.

What am I missing ?

Advertisement

Answer

To my understanding of the Hasura docs, there is no way to reference a field within a query like you can do in SQL. But that does not mean, you can’t do, what you are trying to do. There are three ways of achieving the result that you want:

1. Create a filtered view

CREATE VIEW earliest_articles AS
SELECT Article.*
FROM Article
INNER JOIN Category ON Article.categoryId = Category.categoryId
WHERE Article.publishedDate < Category.createdDate + 3 days

This view should now become available as a query. Docs for views are here.

2. Create a view with a new field

CREATE VIEW articles_with_creation_span AS
SELECT
  Article.*,
  (Article.publishedDate - Category.createdDate) AS since_category_creation
FROM Article
INNER JOIN Category ON Article.categoryId = Category.categoryId

Now you can again query this view and use a filter query on the extra field. This solution is useful if you want to vary the amount of time, that you want to query for. The downside is, that there are now two different article types, it might make sense to hide the regular articles query then.

3. Use a computed field

You can also define computed fields in Hasura. These fields are not only included in the output object type of the corresponding GraphQL type, but they can also be used for querying. Refer to the docs on how to create a computed field. Here you can again, calculate the difference and then use some kind of comparison operator (<) to check if this time is smaller than '3 days'.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement