【发布时间】:2021-11-27 10:49:29
【问题描述】:
在 Node.js 应用程序中,我使用 graphql 来获取数据列表。我创建了两个模型,称为School 和Grade。像 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