Modelling one-to-many table relationships¶
Table of contents
Introduction¶
A one-to-many
relationship between two tables can be established via a foreign key constraint.
Say we have the following two tables in our database schema:
author (
id SERIAL PRIMARY KEY,
name TEXT
)
article (
id SERIAL PRIMARY KEY,
author_id INT
title TEXT
...
)
These two tables are related via a one-to-many
relationship. i.e:
- an
author
can have manyarticles
- an
article
has oneauthor
Step 1: Set up a table relationship in the database¶
This one-to-many
relationship can be established in the database by:
- Adding a foreign key constraint from the
article
table to theauthor
table using theauthor_id
andid
columns of the tables respectively.
This will ensure that the value of author_id
column in the article
table is present in the id
column of
the author
table.
Step 2: Set up GraphQL relationships¶
To access the nested objects via the GraphQL API, create the following relationships:
- Array relationship,
articles
fromauthor
table usingarticle :: author_id -> id
- Object relationship,
author
fromarticle
table usingauthor_id -> author :: id
Step 3: Query using relationships¶
We can now:
fetch a list of authors with their
articles
:GraphiQL1query {
2author {
3id
4name
5articles {
6id
7title
8}
9}
10}
Variablesx1
xxxxxxxxxx
{
"data": {
"author": [
{
"id": 1,
"name": "Justin",
"articles": [
{
"id": 15,
"title": "vel dapibus at"
},
{
"id": 16,
"title": "sem duis aliquam"
}
]
},
{
"id": 2,
"name": "Beltran",
"articles": [
{
"id": 2,
"title": "a nibh"
},
{
"id": 9,
"title": "sit amet"
}
]
}
]
}
}
fetch a list of articles with their
author
:GraphiQL101query {
2article {
3id
4title
5author {
6id
7name
8}
9}
10}
Variables11
xxxxxxxxxx
{
"data": {
"article": [
{
"id": 1,
"title": "sit amet",
"author": {
"id": 4,
"name": "Anjela"
}
},
{
"id": 2,
"title": "a nibh",
"author": {
"id": 2,
"name": "Beltran"
}
}
]
}
}
Was this page helpful?
Thank you for your feedback!