hydra
Search…
Entity Relationships
Define one-to-one, one-to-many and many-to-many relationships between entities

One-To-One (1:1) Relationships

In One-To-One relation, one entity instance is related to only one instance of another entity. One side of the relationship should always derive.
1
type User @entity {
2
name: String!
3
profile: Profile! @derivedFrom(field: "user")
4
}
5
6
type Profile @entity {
7
avatar: String!
8
user: User!
9
}
Copied!
Database tables:
1
user
2
| Column | Type
3
----------|-------
4
| id | character varying
5
| name | character varying
Copied!
1
profile
2
| Column | Type
3
----------|-------
4
| id | character varying
5
| avatar | character varying
6
| userId | character varying FOREIGN KEY UNIQUE CONSTRAINT
Copied!

One-To-Many (1:n) Relationships

In One-To-Many relation, one entity instance is related to multiple instances of the other entity.
1
type User @entity {
2
name: String
3
}
4
5
type Post @entity {
6
title: String
7
author: User!
8
}
Copied!
Database table for the Post entity:
1
post
2
| Column | Type
3
----------|-------
4
| id | character varying
5
| avatar | character varying
6
| authorId | character varying FOREIGN KEY
Copied!
The only difference between 1:1 and 1:n is the unique constraint that 1:1 has.

Many-To-Many (n:n) Relationships

Many-To-Many is a relationship where one entity instance is related to a collection of instances of other entities and vice-versa. In this relationship, one side of the relation must derive.
1
type User @entity {
2
name: String
3
books: [Book!] @derivedFrom(field: "authors")
4
}
5
6
type Book @entity {
7
title: String
8
authors: [User!]
9
}
Copied!
A junction table is created for n:n relationship.
Database tables:
1
book
2
| Column | Type
3
----------|-------
4
| id | character varying
5
| title | character varying
Copied!
1
book_user
2
| Column | Type
3
----------|-------
4
| book_id | character varying
5
| user_id | character varying
Copied!

Reverse Lookups

Defining reverse lookups on an entity allows you to query the other side of the relation. Use @derivedFrom directive to add a reverse lookup to an entity.
Example If we want to access a user's posts from the user entity we should add a derived field to User entity:
1
type User @entity {
2
name: String
3
posts: [Post!] @derivedField(field: "author")
4
}
5
6
type Post @entity {
7
title: String
8
author: User!
9
}
Copied!

Relationships In Mappings

Each GraphQL entity has a corresponding TypeORM entity and we use these entities to perform CRUD operations.
Example
We will create a new post for an existing user:
1
export async function handleNewPost(db: DB, event: SubstrateEvent) {
2
const { userId, title } = event.params;
3
const user = await db.get(User, { where: { id: userId } });
4
5
const newPost = new Post();
6
newPost.title = title;
7
newPost.author = user;
8
9
db.save<Post>(newPost);
10
}
Copied!
Last modified 8mo ago