How to query list of objects with array as an argument in GraphQL
Asked Answered
S

3

64

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?

Subshrub answered 16/11, 2016 at 23:40 Comment(0)
C
78

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]
  }
}
Cerallua answered 17/11, 2016 at 0:1 Comment(2)
what would the schema look like?Gill
what would the [1,2,3] look like when using query variables instead of hardcoding it directly in the query?Strapless
E
1

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
    }
  }
}
Exine answered 30/11, 2021 at 0:12 Comment(2)
allEvents has no argument named \"filter\"". From what I understand the remote side needs to have this option implemented. I don't understand all the hype around graphQL, there is no magic, as api clients, we still need to ask api developper for new features when needed, or do multiples queries in case what we look for is not implemented....Teacup
@Teacup the hype around graphql is mostly because with it you can query multiple services and have just one endpoint. Also when building frontends separately from the backend "headless" you can use that same endpoint for different frontends. With rest apis you have different endpoints for things like products, categories, etcValorize
D
0

In my use case I did as:

query:

vehicleTypes: { name: ["Small", "Minivan"] }

input:

vehicleTypes: VehicleTypesInput

then use like this:

Input VehicleTypesInput {
    name: [String]!
}
Darnley answered 10/10, 2021 at 13:53 Comment(1)
Why do you use an input type on a query?Concertize

© 2022 - 2024 — McMap. All rights reserved.