mysql - Sequelize - 匹配 mySQL 数据库中给定实体的所有记录
问题描述
我有三个 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 |
我在这里面临的问题是我需要获取所有选择了课程 ID 1 和 2 的学生的列表,在上面的示例中是“约翰”。
使用 sequelize 我尝试了以下两个 where 子句,但都给了我不正确的结果。
选项 1)这给了我空的结果集
where: {
course_id: {
[Op.and]: [1,2]
}
}
选项 2)这将返回“John”和“James”。它不应该返回“James”,因为他只订阅了课程 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]
}
}
}]
})
推荐阅读
- c - 时钟功能在操作系统中是如何工作的?
- powershell - 将两个命令合二为一并在 Powershell 中导出为 csv 文件
- excel - VBA 在不同的工作表中查找组并返回前 3 个值和名称
- sql - 在 SQL Server 中为事实表连接多个表的复杂性
- javascript - 在 React.js 中注销一个选项卡时,如何注销一个浏览器中的所有选项卡?
- servicenow - 如何在 ServiceNow 中为我的所有不具有受影响 CI 的事件创建报告?
- json - JQ 无法解析 \u2022 字符
- twig - 如何在不使用 jquery 的情况下获取 twig 中输入的值并在同一页面 twig 中存在的 url 中重用
- python - 如何查找字符串是否包含大写字母和数字
- json - Haskell, Aeson - 有没有更好的方法来解析历史数据?