mysql - Sequelize - 匹配 mySQL 数据库中给定实体的所有记录

标签 mysql sequelize.js

我有三个 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/

相关文章:

javascript - 模型包含选项将属性作为具有定义别名的单个值而不是具有属性的对象返回

php - 要求有金额的条件

node.js - Sequelize : Unhandled rejection TypeError: admin. hasOperation_sav 不是函数

sequelize.js - 是否可以使用 sequelize 中的钩子(Hook)获取插入的行 ID?

mysql - 如何比较和更改 MYSQL 中的值

php - 使用不同的模型/页面插入一行 - CodeIgniter

python - 在Linux上部署Django项目

node.js - 如何使用nodejs导出sql表,sp, View ?

javascript - 如何根据使用选择框选择的值从数据库中检索特定记录?

node.js - Sequelize create 方法返回生成的主键?