我在后端服务器中将sequelize js与nodejs一起用于其余api。当我尝试使用外键将数据插入/更新到关系表中时,sequelize尝试将数据插入错误的列名中。
sessionmessages.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const SessionMessages = sequelize.define('SessionMessages', {
timeLine: DataTypes.INTEGER
}, {
timestamps: false,
freezeTableName: true,
tableName: 'session_messages'
});
SessionMessages.associate = function(models) {
// associations can be defined here
SessionMessages.belongsTo(models.Message, {
onDelete: "CASCADE",
foreignKey: 'messageId',
targetKey: 'id'
});
SessionMessages.belongsTo(models.Session, {
onDelete: "CASCADE",
foreignKey: 'sessionId',
targetKey: 'id'
});
};
return SessionMessages;
};
我用来插入数据的代码非常基本:
const SessionMessages = models.SessionMessages;
const data = {
timeLine: parseInt(req.body.timeLine),
sessionId: parseInt(req.body.sessionId),
messageId: parseInt(req.body.messageId)
};
console.log(data);
SessionMessages.create(data).then(session => {
res.json(session);
});
Executing (default): INSERT INTO `session_messages` (`timeLine`,`MessageId`,`messageId`, `SessionId`, `sessionId`) VALUES (600,NULL,1,NULL,1);
似乎我的外键定义sessionId
和messageId
被忽略了,而添加了SessionId
和MessageId
。