SequelizeJS MySQL-错误的外键查询belongsTo参考

时间:2018-09-24 05:23:13

标签: javascript mysql sql node.js sequelize.js

我在后端服务器中将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);
        });

SQL查询序列尝试运行的是

Executing (default): INSERT INTO `session_messages` (`timeLine`,`MessageId`,`messageId`, `SessionId`, `sessionId`) VALUES (600,NULL,1,NULL,1);

似乎我的外键定义sessionIdmessageId被忽略了,而添加了SessionIdMessageId

0 个答案:

没有答案