首页 > 解决方案 > 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]
}

我在这里想念什么?

提前致谢

标签: mysqlsequelize.js

解决方案


您可以使用它来实现 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]
                }
          }
    }]
})

推荐阅读