GraphQL relations

This tutorial assumes that you have successfully completed the Get started with GraphQL tutorial, and that you still have the Fauna Console open in a browser tab/window, on the GraphQL Playground screen.

If your Fauna Console session has expired:

  1. Log in again.

  2. Select the graphql database.

  3. Click the GRAPHQL button in the left navigation.

To form bi-directional relations in GraphQL requires using the @relation directive. @relation connects an attribute in a GraphQL schema to another GraphQL type.

In this tutorial, we are going to extend the current schema (established in the Get started with GraphQL tutorial). Instead of simply storing todo records, we are going to categorize our todos using lists.

The steps:

  1. Create a new schema file

    Create the file schema-relations.gql with the following content (or download it here):

    type Todo {
      title: String!
      completed: Boolean!
      list: List
    }
    
    type List {
      title: String!
      todos: [Todo] @relation
    }
    
    type Query {
      allTodos: [Todo!]
      todosByCompletedFlag(completed: Boolean!): [Todo!]
      allLists: [List!]
    }
  2. Import the new GraphQL schema into Fauna

    Click the UPDATE SCHEMA button on the GraphQL Playground screen in your browser, which opens your browser’s file selector. Select the schema-relations.gql file, and click the file selector’s Open button.

    This new schema only updates collections (and associated indexes) with the same name. Any other collections are unaffected.
  3. Create a todo list

    With the new schema in place (which preserves any existing todo items), we can now create a list that todo items can belong to.

    Copy the following GraphQL mutation query:

    mutation CreateAList {
      createList(data: {
        title: "Development"
      }) {
        title
        _id
      }
    }

    Then click the "new tab" + button on the GraphQL Playground screen in your browser (at the top left, just right of the last query tab). Then paste the query into the left panel, and click the "Play" button. The query should execute and the response should appear in the right panel:

    {
      "data": {
        "createList": {
          "title": "Development",
          "_id": "234458015536775681"
        }
      }
    }
    Copy the value for _id for use in the next step.
  4. Create a todo related to the list

    Now that we have a todo list, how do we create related todos? We use the connect field on a todo’s list attribute to use its defined relationship to make the connection for us.

    Copy the following GraphQL mutation query:

    mutation CreateAListedTodo {
      createTodo(data: {
        title: "Learn how to GraphQL with FaunaDB"
        completed: false
        list: { connect: "234458015536775681" }
      }) {
        title
        completed
        list {
          title
        }
      }
    }

    Then click the "new tab" + button on the GraphQL Playground screen in your browser (at the top left, just right of the last query tab). Paste the query into the left panel. Replace 234458015536775681 in the query with the value of _id from the previous step. Finally, click the "Play" button. The query should execute and the response should appear in the right panel:

    {
      "data": {
        "createTodo": {
          "title": "Learn how to GraphQL with FaunaDB",
          "completed": false,
          "list": {
            "title": "Development"
          }
        }
      }
    }
  5. Query the list for related todos

    Now that we have a todo that is related to the list, let’s verify that situation.

    Copy the following GraphQL query:

    query FindAListByID {
      findListByID(id: "234458015536775681") {
        title
        todos {
          data {
            title
          	completed
          }
        }
      }
    }

    Then click the "new tab" + button in GraphQL Playground (at the top left, just right of the last query tab). Paste the query into the left panel. Replace 234458015536775681 in the query with the value of _id from the Create a todo list step. Finally, click the "Play" button. The query should execute and the response should appear in the right panel:

    {
      "data": {
        "findListByID": {
          "title": "Development",
          "todos": {
            "data": [
              {
                "title": "Learn how to GraphQL with FaunaDB",
                "completed": false
              }
            ]
          }
        }
      }
    }
  6. Query all todos

    So, what happened to the todo that we created in Get started with GraphQL? Nothing! It just isn’t associated with a list. Let’s check that this is true.

    Copy the following GraphQL query:

    query FindAllTodos {
      allTodos {
        data {
          _id
          title
          completed
          list {
            title
          }
        }
      }
    }

    Then click the "new tab" + button on the GraphQL Playground screen in your browser (at the top left, just right of the last query tab). Paste the query into the left panel. Finally, click the "Play" button. The query should execute and the response should appear in the right panel:

    {
      "data": {
        "allTodos": {
          "data": [
            {
              "_id": "234367997153640967",
              "title": "Build an awesome app!",
              "completed": false,
              "list": null
            },
            {
              "_id": "234458197639823873",
              "title": "Learn how to GraphQL with FaunaDB",
              "completed": false,
              "list": {
                "title": "Development"
              }
            }
          ]
        }
      }
    }

    Notice that the first todo shows that its list field is null. That means that it is not associated with a list.

  7. Update the first todo to join the list

    Let’s update the first todo so that it is associated with the "Development" list.

    Copy the following GraphQL query:

    mutation UpdateATodo {
      updateTodo(id: "234367997153640967", data: {
        title: "Build an awesome app!"
        completed: true
        list: { connect: "234458015536775681" }
      }) {
        title
        completed
        list {
          title
        }
      }
    }

    Then click the "new tab" + button on the GraphQL Playground screen in your browser (at the top left, just right of the last query tab). Paste the query into the left panel. Replace 234367997153640967 in the query with the id of the todo from the previous step, and replace 234458015536775681 with the value of _id from the Create a todo list step. Finally, click the "Play" button. The query should execute and the response should appear in the right panel:

    {
      "data": {
        "updateTodo": {
          "title": "Build an awesome app!",
          "completed": true,
          "list": {
            "title": "Development"
          }
        }
      }
    }

    Notice that we used connect to associate the todo with the list’s id. We also change the completed field to true. We didn’t change the title, but we had to provide it because the title field is marked as required (due to the exclamation mark in the schema).

  8. Create a list with its own todos

    It is possible to bulk-create related documents using the create field. create gives access to the underlying collection, so you can add (or update) a list with a handful of todos in a single GraphQL mutation query.

    Copy the following GraphQL query:

    mutation CreateListWithTodos {
      createList(data: {
        title: "The Basics",
          todos: {
            create: [
              {completed: false, title: "Water"},
              {completed: false, title: "Food"},
              {completed: false, title: "Shelter"}
            ]
          },
      }) {
        _id
        title
        todos {
          data {
            title
          }
        }
      }
    }

    Then click the "new tab" + button on the GraphQL Playground screen in your browser (at the top left, just right of the last query tab). Paste the query into the left panel. Finally, click the "Play" button. The query should execute and the response should appear in the right panel:

    {
      "data": {
        "createList": {
          "_id": "234460851537445380",
          "title": "The Basics",
          "todos": {
            "data": [
              {
                "title": "Water"
              },
              {
                "title": "Food"
              },
              {
                "title": "Shelter"
              }
            ]
          }
        }
      }
    }

Conclusion

This tutorial has demonstrated how to setup GraphQL relations, how to create and update documents that use relations, and how to bulk-create related documents.

For more information on GraphQL relations, see Relations.

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!