GraphQL object association

Hi in this post we are going to learn about the object association in GraphQL.

Note: last GraphQL chapter was GraphQL returning an array of data

If we run our client we are going to see how each “company” have an id that is used for navigation:

Next let add a new type that represent our company in schema.graphql file:

type Query {
  jobs: [Job]
}

type Company {
  id: ID!
  name: String
  description: String
}

type Job {
  id: ID!
  title: String
  description: String
}

And the Job type can return a company and also could be use a custom type for that:

So in this way we represent association between different objects

Ok, now if we try to run this query we are going to receive “null” value for company:

Data return by a resolver is missing a certain field that will result a “null” value.

Now, we need to adjust our resolver declaring a Job resolver, so first let’s look our “fake data” (that is simulate the database), so if you see we have a “companyId” this is what we call a “foreign key” in relational database.

We can use the “companyId” to fetch the company with the same Id.

Now, go to resolvers.js and let’s add a resolver for “Job” with the company field:

So we are saying return the company who id is same as the company id of this job:

That’s why this functions are called resolvers because resolve, this function resolve a company for a given job.

Finally export the Job.

By Cristina Rojas.