2.5 Objects Relationship

I am just going to bring back this image for one second:

At the database layer, we have figured out how to relate two or more tables. If you run an SQL command on the database, you can construct a query that fetches all the users that belong to an account.

Unfortunately, we are not running SQL — we are running GraphQL and GraphQL does not know about this relationship. We need to tell Hasura explicitly that it should expose the tables relationships we have as objects relationships in GraphQL.

This is beneficial in two major ways:

  1. You can query entities and attach related data using objects or arrays to them
  2. When we get to authorizations and permissions, we need object relationships to control access between associated data. For example, if a user can only access accounts the user is invited to, a simple table relationship won’t tell Hasura what the user has access to. With object relationships setup, we can use the Hasura permissions system to define fine-grained access control. (Don’t worry if this does not make enough sense now, we will learn more about it in upcoming sections.)

Objectives

  • Setup object relationships for table relationships
  • Learn the difference between objects and arrays in one-to-many or many-to-many relationships

[Challenge] Nested Query

To prove that we cannot currently query users who belong to an account or vice versa, go to Query Explorer in the GraphiQL and expand the account field. We can query access_token, account_name and id but what we cannot query yet, the users attached to each account

Exercise 1: Create Object Relationships

Task 1: account to account_user object relationship

Head back to the Data tab and select the account table. Next, click on the Relationships tab, and you should see that Hasura is already suggesting an array (object) relationship between account and account_user:

Click on the Add button, and that’s all you need to do to setup an object relationship from the account side.

Task 2: user to account_user object relationship

Repeat the steps we saw in accounts for the user and add the suggested array (object) relationship:

Task 3: user/account to account_user array relationship

Lastly, we need to go to the account_user table and add another object relationship for the user and the account table. This will also be suggested to you once you go to the Relationships tab in the account_user table:

[Solution] Nested Query

If you try to query once more, you should see that we can now access nested objects and arrays: