Modeling One-to-Many Table Relationships
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:
authors (
id SERIAL PRIMARY KEY,
name TEXT
)
articles (
id SERIAL PRIMARY KEY,
author_id INT
title TEXT
...
)
These two tables are related via a one-to-many relationship. i.e:
- an
authorcan have manyarticles - an
articlehas 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
articlestable to theauthorstable using theauthor_idandidcolumns of the tables respectively.
This will ensure that the value of author_id column in the articles table is present in the id column of the
authors table.
Step 2: Set up GraphQL relationships
To access the nested objects via the GraphQL API, create the following relationships:
- Array relationship,
articlesfromauthorstable usingarticles :: author_id -> id - Object relationship,
authorfromarticlestable usingauthor_id -> authors :: id
Query using one-to-many relationships
We can now:
- fetch a list of
authorswith theirarticles:
GraphiQL
Query Variables
Request Headers
No Schema Available
- fetch a list of
articleswith theirauthor:
GraphiQL
Query Variables
Request Headers
No Schema Available
Insert using one-to-many relationships
We can now:
- insert an
authorwith theirarticleswhere the author might already exist (assume uniquenameforauthor):
GraphiQL
Query Variables
Request Headers
No Schema Available
- insert
articleswith theirauthorwhere theauthormight already exist (assume uniquenameforauthor):
GraphiQL
Query Variables
Request Headers
No Schema Available
Note
You can avoid the on_conflict clause if you will never have conflicts.