node.js sequelize 多表查询
三个模型:
1.学生模型,包含 id,name
2.分数模型,包含id,studentId,分数
3.爱好模型,包含id,studentId,爱好
请问在sequelize中如何查询出学生的姓名,分数及爱好?官网介绍的都是二个表的关联查询,三个或更多的就没有说了!
关于#node#的问题,如何解决?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
菜喵007 2023-05-08 09:09关注const Student = sequelize.define('student', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: { type: DataTypes.STRING, allowNull: false } }); const Score = sequelize.define('score', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, score: { type: DataTypes.INTEGER, allowNull: false } }); const Hobby = sequelize.define('hobby', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, hobby: { type: DataTypes.STRING, allowNull: false } }); // 关系配置 Student.hasMany(Score); Score.belongsTo(Student); Student.hasMany(Hobby); Hobby.belongsTo(Student); // 查询学生、分数和爱好 Student.findAll({ attributes: ['name'], include: [{ model: Score, attributes: ['score'] }, { model: Hobby, attributes: ['hobby'] }] })本回答被题主选为最佳回答 , 对您是否有帮助呢?解决评论 打赏 举报无用 1