Relationships
The Fuel indexer service supports foreign key relationships and constraints. There are two types of relationship specifications: implicit and explicit.
IMPORTANT:
Implicit foreign keys do not require a
@joindirective. When using implicit foreign key references, merely add the referenced object as a field type (shown below). A lookup will automagically be done to add a foreign key constraint using this object's'idfield.Note that implicit foreign key relationships only use the
idfield on the referenced table. If you plan to use implicit foreign keys, the object being referenced must have anidfield.In contrast, explicit foreign keys do require a
@joindirective. Explicit foreign key references work similarly to implicit foreign keys; however, when using explicit foreign key references, you must add a@joindirective after your object type. This@joindirective includes the field in your foreign object that you would like to reference (shown below).
Let's learn how to use each foreign key type by looking at some GraphQL schema examples.
Usage
Implicit foreign keys
type Library @entity {
id: ID!
name: String!
}
type Book @entity {
id: ID!
library: Library!
}
Given the above schema, two entities will be created: a Book entity, and a Library entity. As you can see, we add the Book entity as an attribute on the Library entity, thus conveying that we want a one-to-many or one-to-one relationship between Library and Book. This means that for a given Book, we may also fetch the associated Library entity. It also means that the field Book.library will be an ID scalar type that references Library.id.
Explicit foreign keys
type Library @entity {
id: ID!
name: String! @unique
}
type Book @entity {
id: ID!
library: Library! join(on:name)
}
For the most part, this works the same way as implicit foreign key usage. However, as you can see, instead of implicitly using Library.id as the reference column for our Library field type on the Book object, we're explicitly specifying that we want Library.name to serve as our foreign key for the Book.library field. Also, please note that since we're using Library.name in our foreign key constraint, that column is required to be unique (via the @unique directive).