Your first GraphQL API
This article is part of series in Your first GraphQL API:
- Your first GraphQL API - Nested Queries
- Your first GraphQL API - Introduction
- Your first GraphQL API - Pagination
- Your first GraphQL API - Sorting
- Your first GraphQL API - Search
Typically our database is designed with some relationships. When retrieving data from our GraphQL, we would want them to present in a relationship hierarchy as well.
In this tutorial, we will learn how to build nested queries using Youshido/GraphQL.
In our blog example, there is a series of articles and each article belongs to an author. When retrieving articles' data, it makes more sense to fetch belonging author's data as well instead of "author_id".
Table Of Content
1. Add AuthorType.php
Apparently, we need AuthorType in order to resolve the type.
Add src/Type/AuthorType.php
As we can see, it is a super simple type with an id(integer) and name(string) fields.
2. Add AuthorField.php
We will use AuthorField to resolve the request.
Add src/Field/AuthorField.php
Let's take a close look at the resolve method.
When getting the $authorId, we fetch it directly from the $value variable as shown below:
This is because $value is configured to contain values from the parent. Which is article is our case. And because we know article will return an author_id, we fetch it directly from $value variable.
The rest of the code is self-explanatory, we find the author that article belongs to using our fake repository and return it.
3. Modify ArticleField.php
We are almost done. The last piece is to modify ArticleField.php to wire ArticleType and AuthorType up.
To do this, open src/Type/ArticleType.php. And change
to
Our final src/Type/ArticleType.php file looks like this after the modification:
In the first tutorial, we are getting articles data using a query similar to:
Now we can get full author data using:
The magic here is that, if you do not ask for author's data. The resolve method(AuthorField::resolve) will never be called. The Youshido/GraphQL library takes care of the job of figuring out which resolve methods to call.
4. The End
Hopefully this simple tutorial helped you with your development.
If you like our post, please follow us on Twitter
and help spread the word. We need your support to continue.
If you have questions or find our mistakes in above tutorial, do leave a comment below to let us
know.