使用Epilogue JS和Sequelize,我有两个资源Student
和Course
,它们之间存在m2m关系。我想创建一个新的Student
并将该学生实例与现有课程相关联。
当我POST
新学生并在有效负载中包含课程信息时,Epilogue / Sequelize将尝试创建新学生并根据嵌套的有效负载创建新课程。这将导致验证错误,因为这些课程已经存在。
const Student = db.define('student', {
id: Sequelize.UUID,
name: Sequelize.STRING
});
const Course = db.define('course', {
id: Sequelize.UUID,
name: Sequelize.STRING
});
Student.belongsToMany(Course, {through: 'student_courses'});
Course.belongsToMany(Student, {through: 'student_courses'});
const StudentResource = epilogue.resource({
model: Student,
endpoints: ['/student', '/student/:id'],
include: [{
model: Course
}];
});
我想发布一名新学生并与现有课程相关联,例如:
// POST /users/
{
name: "Sally",
courses: [
{id: 123, name: "math"},
{id: 456, name: "science"}
]
}
然而,Epilogue / Sequelize将失败,因为这些课程已经存在:
{
"message": "Validation error",
"errors": [
{
"field": "id",
"message": "id must be unique"
}
]
}
答案 0 :(得分:0)
对于结语是如何工作的并不是很好,但是纯粹通过续集来做,你可以使用set<Association>
方法
有些事情,
student = model.student.create(/*some properties*/)
student.setCourse(course_id)
有关详情,请参阅this问题