Given the following database schema:
Table items
users.userId
Table users
Now, if I wanted to query all items including the owner's username, so my GraphQL query would look like this:
items {
title
ownerId
username
}
How would that look like on the backend? Would I have to introduce a new entity like
record class ItemWithUsername(
string Title,
string OwnerId,
string Username
)
and write an resolver for it or is there a more generic solution (e.g. not having to write a new type) to this? I know a user of my GraphQL API could first query all items (only ownerId, username) and then query for the relevant username from users (via ownerId), but that would require many network round trips, which is what I want to prevent.
Normally for a many-to-one relationship you would use two types:
type Item {
id: ID!
title: String!
owner: User!
}
type User {
id: ID!
username: String!
items: [Item]
}
Then you would have a query like:
query items {
id
title
owner {
id
username
}
}
But you could also query in the one-to-many direction:
query users {
id
username
items {
id
title
}
}
You might enjoy reading my post on GraphQL for SQL Developers which covers the differences in how you model systems using SQL and GraphQL. One of the key points is that you rarely (if ever) include foreign keys in your types. Instead you include a reference to the other type itself.
ps. The rationale for including the id
in your queries even if you're not displaying them is that it makes the results cacheable on the client.