Search code examples
node.jspostgresqlgraphqlsequelize.jsassociations

Node.js - How to get associated model data using graphql?


In Node.js app, I am using graphql to get the list of data. I have created two models called School and Grade. Association for these models like School has many Grades and Grade belongs to School. While querying I am getting null value for associated model.

In model school.js,

module.exports = (sequelize, Sequelize) => {
 const School = sequelize.define("school", {
  name: {
   type: Sequelize.STRING,
  },
  email: {
    type: Sequelize.STRING,
  },
 });

 School.associate = function (models) {
  School.hasMany(models.Grade, { foreignKey: "school_id" });
 };

 return School;
};

In typeDefs.graphql,

type Query {
  getSchoolDetails: [School]
  getSchoolDetail(id: ID!): School
  getGradeDetails: [Grade]
}

type School {
  id: ID!
  name: String
  email: String
  grades: [Grade]
}

type Grade {
  id: ID!
  school_id: ID!
  name: String
  school: School
}

In resolvers.js,

const Query = {
 getSchoolDetails: async () => {
  try {
    const schools = await school.findAll();
    return schools;
  } catch (err) {
    console.log(err);
  }
 },
 getSchoolDetail: async (root, { id }) => {
  try {
    const scl = await school.findByPk(id);
    return scl;
  } catch (err) {
    console.log(err);
  }
 },
 getGradeDetails: async () => {
  try {
    const grades = await grade.findAll({});
    return grades;
  } catch (err) {
    console.log(err);
  }
 },
}

In playground when I query like,

query {
 getSchoolDetails{
  id
  name
  email
  grades{
    name
  }
 }
}

Output for this is,

{
 "data": {
   "getSchoolDetails": [
    {
      "id": "1",
      "name": "Rotary West School",
      "email": "[email protected]",
      "grades": null
    },
    {
      "id": "2",
      "name": "Excel Public School",
      "email": "[email protected]",
      "grades": null
    },
  ]
}

Same way when I query to get Grades will get school as null. I am learning nodejs relations with graphql, please help me to solve this.


Solution

  • You have to use include with your queries in resolvers.js file like below

    getSchoolDetails: async () => {
                    try {
                        const schools = await school.findAll({
                            include: [{ model: Grade }],
                        });
                        return schools;
                    } catch (err) {
                        console.log(err);
                    }
                },
    

    This Will get all the grades associated with schools

    And if you want to include school with grade you have to associate grade with school using Grades belongsTo school