我有三个 MySQL (v8) 表
表格1:
students (contains details of all students)
- id
- full_name
- email
记录:
| id | full_name | email |
|----|-----------|-------------------|
| 1 | John | john@example.com |
| 2 | Adam | adam@example.com |
| 3 | James | james@example.com |
| 4 | Jane | jane@example.com |
表 2:
courses (contains all courses)
- id
- title
记录:
| id | title |
|----|--------|
| 1 | PHP |
| 2 | Python |
| 3 | .Net |
| 4 | HTML |
表3:
student_courses (this table contains which student has subscribed to what courses)
- student_id
- course_id
记录:
| id | student_id | course_id |
|----|------------|-----------|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 3 |
| 4 | 3 | 1 |
我在这里面临的问题是我需要获得选择了类(class) ID 1 和 2 的所有学生的列表,在上面的例子中是“约翰”。
使用 sequelize 我尝试了以下两个 where 子句,但都给了我错误的结果。
选项 1) 这给了我空的结果集
where: {
course_id: {
[Op.and]: [1,2]
}
}
选项 2) 这将返回“John”和“James”。它不应该返回“James”,因为他只订阅了类(class) ID 1。
where: {
course_id: [1, 2]
}
我在这里缺少什么?
提前致谢
最佳答案
您可以通过使用它来实现 N:M 关联,更多信息可以在这里找到 http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-belongsToMany
//add required associations
students.associate = (models) => {
students.belongsToMany(models.courses, {
through: 'student_courses',
foreignKey: 'student_id'
});
};
// now query the db like this
db.students.findAll({
where: { full_name : 'john'},
include: [{
model: db.courses,
where: {
id: {
[Op.and]: [1,2]
}
}
}]
})
关于mysql - Sequelize - 匹配 mySQL 数据库中给定实体的所有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55998478/