【发布时间】:2020-03-31 03:14:33
【问题描述】:
我是关系数据库的新手。我正在使用 node js 并表示后端,REST API 和数据库是 Postgresql。我正在使用 Sequelize 进行连接和模型。我创建了两个模型,一个是学生,另一个是课程。我的目标是一个学生可以有多个课程,并且还想防止重复的学生姓名、电话、电子邮件。我成功连接到数据库并能够发布请求。当然,我是这样发帖的,Image of course post request。通过测试我正在使用 Postman 的应用程序。但是当我试图从学生或课程中获得请求时。 我认为学生与课程之间没有任何关系。这是可视化students get request 和courses get request。 这是live code。
这是我的学生模型
const Student = con.define("student", {
id: {
type: sequelize.INTEGER,
primaryKey: true
},
name: {
type: sequelize.STRING,
allowNull: false
},
birthday: {
type: sequelize.DATEONLY,
allowNull: false
},
address: {
type: sequelize.STRING,
allowNull: false
},
zipcode: {
type: sequelize.INTEGER,
allowNull: false
},
city: {
type: sequelize.STRING,
allowNull: false
},
phone: {
type: sequelize.BIGINT,
allowNull: false
},
email: {
type: sequelize.STRING,
allowNull: false,
validate: {
isEmail: true
}
}
});
这是课程模型
const Course = con.define("course", {
name: { type: sequelize.STRING },
startdate: { type: sequelize.DATEONLY },
enddate: { type: sequelize.DATEONLY },
studentId: { type: sequelize.INTEGER, foreignKey: true }
});
这是我的多对多关系设置
const StudentCourse = con.define("studentCourses", {
id: {
type: sequelize.INTEGER,
primaryKey: true
},
courseId: { type: sequelize.INTEGER, foreignKey: true },
studentId: { type: sequelize.INTEGER, foreignKey: true }
});
Student.belongsToMany(Course, { through: StudentCourse, as: "courses" });
Course.belongsToMany(Student, { through: StudentCourse, as: "students" });
//con.sync({ force: true });
module.exports = { Student, Course, StudentCourse };
这是我的 REST API 设置。学生和课程发帖请求
//Student post request
app.post("/students", async (req, res, next) => {
try {
const logs = new Student(req.body);
const entry = await logs.save();
res.json(entry);
} catch (error) {
if (error.name === "ValidationError") {
res.status(422);
}
next(error);
}
});
//Course post request
app.post("/courses", async (req, res, next) => {
try {
const logs = new Course(req.body);
const entry = await logs.save();
res.json(entry);
} catch (error) {
if (error.name === "ValidationError") {
res.status(422);
}
next(error);
}
});
*这是我没有看到结果的学生和课程的获取请求设置
app.get("/student", async (req, res, next) => {
try {
await Student.findAll({
include: {
model: Course,
through: StudentCourse,
as: "courses"
}
}).then(docs => {
res.json(docs);
});
} catch (error) {
console.log(error);
}
});
app.get("/course", async (req, res, next) => {
try {
await Course.findAll({
include: {
model: Student,
through: StudentCourse,
as: "students"
}
}).then(docs => {
res.json(docs);
});
} catch (error) {
console.log(error);
}
});
【问题讨论】:
标签: node.js express sequelize.js many-to-many