I'm trying to query a list of objects having array of IDs. Something similar to following SQL query:
SELECT name FROM events WHERE id IN(1,2,3,...);
How do I achieve this in GraphQL?
When you're passing arguments in code, it's generally better to avoid constructing the whole query string yourself. Instead, you can use $ syntax to define variables in your query, and pass the variables as a separate map. . then(data => console.
Multiple arguments can be used together in the same query. For example, you can use the where argument to filter the results and then use the order_by argument to sort them.
The __typename field returns the object type's name as a String (e.g., Book or Author ). GraphQL clients use an object's __typename for many purposes, such as to determine which type was returned by a field that can return multiple types (i.e., a union or interface).
Just like fields, there are no type restrictions. Arguments can be of different types, too. The result of the previous query with the id argument will look like the following: One possible pitfall here is that GraphQL queries look almost the same for single items and lists of items.
If you've seen a GraphQL query before, you know that the GraphQL query language is basically about selecting fields on objects. So, for example, in the following query: For the object returned by hero, we select the name and appearsIn fields
Unlike languages like JavaScript and Python where functions take a list of ordered arguments, all arguments in GraphQL are passed by name specifically. In this case, the length field has one defined argument, unit. Arguments can be either required or optional.
GraphQL has list types which are ordered lists containing items of other types. The following examples use the GraphQL Schema Definition Language (SDL). Fields may return a single scalar value (eg String ), or a list of scalar values (eg, [String], a list of strings):
You can definitely query with an array of values! Here's what the query itself would look like:
{
events(containsId: [1,2,3]) {
...
}
}
And the type would look something like:
const eventsType = new GraphQLObjectType({
name: 'events',
type: // your type definition for events,
args: {
containsId: new GraphQLList(GraphQLID)
},
...
});
If you wanted to parameterize this query, here's an example of that:
{
query: `
query events ($containsId: [Int]) {
events(containsId: $containsId) {
id
name
}
}
`,
variables: {
containsId: [1,2,3]
}
}
I just do this:
query nameOfYourQuery {
allEvents(filter: { id: { in: [1,2,3] } }) {
nodes {
name
}
}
}
If the array is a variable, then it would look like this (in Gatsby, at least):
query nameOfYourQuery($arrayOfID: [String]) {
allEvents(filter: { id: { in: $arrayOfID: [String] } }) {
nodes {
name
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With