【问题标题】:Node.js - How to get associated model data using graphql?Node.js - 如何使用 graphql 获取关联的模型数据?
【发布时间】:2021-11-27 10:49:29
【问题描述】:

在 Node.js 应用程序中,我使用 graphql 来获取数据列表。我创建了两个模型,称为SchoolGrade。像 School 这样的模型的关联有很多 Grades 并且 Grade 属于 School。 查询时,我得到 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的关系,请帮我解决这个问题。

【问题讨论】:

    标签: node.js postgresql graphql sequelize.js associations


    【解决方案1】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-18
      • 2021-04-28
      • 2019-07-07
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 2017-11-09
      相关资源
      最近更新 更多