node.js sequelize 多表查询
三个模型:
1.学生模型,包含 id,name
2.分数模型,包含id,studentId,分数
3.爱好模型,包含id,studentId,爱好
请问在sequelize中如何查询出学生的姓名,分数及爱好?官网介绍的都是二个表的关联查询,三个或更多的就没有说了!
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']
}]
})
按照你的答复,执行如下 :
SELECT student
.id
, student
.name
, scores
.id
AS scores.id
, scores
.score
AS scores.score
, hobbies
.id
AS hobbies.id
, hobbies
.hobby
AS hobbies.hobby
FROM students
AS student
LEFT OUTER JOIN scores
AS scores
ON student
.id
= scores
.studentId
LEFT OUTER JOIN hobbies
AS hobbies
ON student
.id
= hobbies
.studentId
;"
错误出现在scores.
studentId . scores这个表中没有studentId这个字段
hobbies.
studentId`.hobbles这个表中没studentId这个字体.
请问如何处理?