1. 16
    Add a Product Relation to Shop to understand Document Model Relationship in Fauna
    2m 11s

Add a Product Relation to Shop to understand Document Model Relationship in Fauna

Shadid Haque
InstructorShadid Haque
Share this video with your friends

Social Share Links

Send Tweet

If you have been poking around the queries at this point in the course, you might notice that when you query for a product, you can get all the associated shop information. This is because we defined the @relation on the Shop property within Product. This allowed Fauna to create an index behind the scenes to easily fetch this data.

We haven't done the same for the Product property on the Shop so we can't access the data. When we add a new @relation to Product we can then grab all the product information from shop queries that we like.

This is based on the Document Model Relationship in Fauna that you can read more about here.

Instructor: [0:00] We're back here in the GraphQL playground inside Fauna. In this tab here, I have a query to find a product by its ID. Notice that in the sub-selection, I can select shop and I can get the information about the shop this product belongs to, such as name and the ID of the shop.

[0:19] In the next tab, I'm trying to find the same shop by its ID. I defined the products sub-selection for this query. However, when we run this query, something interesting happens. The query does not return any product information, it returns an empty array.

[0:36] Let's take a look at our schema to understand what's going on here. On line 15, we have this relation directive defined. Because of this relation directive, Fauna creates an index behind the scene. When we run the query, this index helps us to get the shop information.

[0:52] We can add this relation directive to line 5 as well. That way, we'll be able to get all the products that belongs to a shop. Let's save this and merge our GraphQL schema.

[1:06] We have to change the query slightly and include data because it's returning an array. When we run it, we get information about the products that belong to this shop. Behind the scene, it created a new index.

[1:22] If we want to run this query from our front-end, we need read privilege on this index. I'm going to go to security roles and front-end role and give read privilege to this newly created index. Now, we can call this query from our front-end.

[1:41] You can define many complex data relationships in Fauna. Fauna is a document relational database. It combines the flexibility of JSON documents with the relationship and querying power of a traditional database. To learn more, visit Fauna's official documentation page.

[1:58] Finally, let's go back to our code and in new shop form file, we can get rid of line 19. Now that we have relationship defined, we don't need this hard-coded empty array.