我有问题:"不与"相关联。我想要一对多关联。这是我的代码Index.js
fs.readdirSync(__dirname)
.filter(file => {
return file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js';
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize);
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.Sequelize = Sequelize;
db.sequelize = sequelize;
module.exports = db;
这是course.js
module.exports = (sequelize, Sequelize) => {
const Course = sequelize.define(
'course',
{
idCourse: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
field: 'idcourse',
},
nameOfCourse: {
type: Sequelize.STRING,
field: 'nameofcourse',
},
idLevel: {
type: Sequelize.INTEGER,
field: 'idlevel',
},
idTypeOfCourse: {
type: Sequelize.INTEGER,
field: 'idtypeofcourse',
},
startDate: {
type: Sequelize.DATE,
field: 'startdate',
},
endDate: {
type: Sequelize.DATE,
field: 'enddate',
},
fee: {
type: Sequelize.BIGINT,
field: 'fee',
},
isDeleted: {
type: Sequelize.BOOLEAN,
field: 'isdeleted',
},
},
{
freezeTableName: true,
timestamps: false,
createdAt: false,
updatedAt: false,
}
);
Course.associate = function (models) {
models.course.belongsToMany(models.bill, {
through: models.billinfo,
as: 'bill',
foreignKey: 'idCourse',
});
models.course.belongsTo(models.typeofcourse, {
foreignKey: 'idTypeOfCourse',
sourceKey: 'idCourse',
as: 'typeofcourse',
});
};
return Course;
};
这里是TypeOfCourse.js
module.exports = (sequelize, Sequelize) => {
const TypeOfCourse = sequelize.define(
'typeofcourse',
{
idTypeOfCourse: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
field: 'idtypeofcourse',
},
nameOfType: {
type: Sequelize.STRING,
field: 'nameoftype',
},
language: {
type: Sequelize.STRING,
field: 'language',
},
tags: {
type: Sequelize.ARRAY(Sequelize.TEXT),
field: 'tags',
},
isDeleted: {
type: Sequelize.BOOLEAN,
field: 'isdeleted',
},
},
{
freezeTableName: true,
timestamps: false,
createdAt: false,
updatedAt: false,
}
);
TypeOfCourse.associate = function (models) {
models.typeofcourse.hasMany(models.course, {
foreignKey: 'idTypeOfCourse',
as: 'course',
});
};
return TypeOfCourse;
};
在Course .controller.js中,我定义了函数findAll Course,并希望显示关于typeOfCourse的信息
exports.findAll = (req, res) => {
Course.findAll({
include: [
{
model: TypeOfCourse,
as: 'typeofcourse',
through: { attributes: [] },
},
],
})
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message: err.message || 'Some error occurred while retrieving course.',
});
});
};
但是当我发送请求获得课程。此消息响应:
{
"message": "typeofcourse is not associated to course!"
}
哪里我错了,如何解决这个错误。非常感谢。
您可以使用hasMany
关联,它将创建一个带有连接表的N:M关联
Course.hasMany(TypeOfCourse, {
foreignKey: { name: 'idCourse' },
targetKey: 'idCourse',
constraints: false,
as: 'typeOfCourses',
}),
```