Node.js - 如何使用graphql获取关联的模型数据?

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

在 Node.js 应用程序中,我使用 graphql 获取数据列表。我创建了两个名为 SchoolGrade 的模型。这些模型的协会,如学校有很多年级,年级属于学校。 查询时我得到关联模型的 null 值。

型号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;
};

在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
}

在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);
  }
 },
}

在操场上当我查询时,

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

这个的输出是,

{
 "data": {
   "getSchoolDetails": [
    {
      "id": "1",
      "name": "Rotary West School",
      "email": "rotary@gmail.com",
      "grades": null
    },
    {
      "id": "2",
      "name": "Excel Public School",
      "email": "excel@gmail.com",
      "grades": null
    },
  ]
}

当我查询获取成绩时,同样的方式会像 null 一样得到学校。我正在学习nodejs与graphql的关系,请帮我解决这个问题。

您必须在 resolvers.js 文件中使用 include 查询,如下所示

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

这将获得与学校相关的所有成绩

如果你想 include school with grade you have to associate grade with school using Grades belongsTo school