Sequelize - 使用ALTER TABLE,Mysql foreignKey ADD CONSTRAINT失败

时间:2017-09-19 09:58:30

标签: mysql node.js foreign-keys sequelize.js alter

我正在尝试使用以下Sequelize模型创建两个表:

const Sequelize = require('sequelize');

module.exports = function (db) {
const Product = db.define('product', {
    intProductID: {
        type: Sequelize.INTEGER(11),
        primaryKey: true,
        autoIncrement: true,
        allowNull: false

    },
    strName: {
        type: Sequelize.STRING
    },
    douPrice: {
        type: Sequelize.DOUBLE
    }
});

return Product;
}

const Sequelize = require('sequelize');

module.exports = function(db){
const User = db.define('user', {
    intUserID:{
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false
    },
    strEmail:{
        type:Sequelize.STRING
    },

    strPassword:{
        type:Sequelize.STRING
    },

    strFirstName: {
      type: Sequelize.STRING
    },
    strLastName: {
      type: Sequelize.STRING
    }
});

return User;
}

添加这两个模型后,我尝试将它们与以下代码相关联:

Product.belongsTo(
        User,
        {
            foreignKey: {
                name: 'intCreateUserID',
                allowNull: false
            },
            foreignKeyConstraint: true
        }
    );

第一次发生这种情况,效果很好。但是一段时间后,它会尝试多次添加约束。我不断收到以下错误:

SequelizeDatabaseError: Can't create table 'shop.#sql-4d23_2563b' (errno: 121)
code: 'ER_CANT_CREATE_TABLE',
 errno: 1005,
 sqlState: '#HY000',
 sql: 'ALTER TABLE `products` ADD CONSTRAINT `products_intUpdateUserID_foreign_idx` FOREIGN KEY (`intUpdateUserID`) REFERENCES `users` (`intUserID`) ON DELETE NO ACTION ON UPDATE CASCADE;'

我试图在mysql控制台上重现错误并复制粘贴查询。我注意到它因为现有的外键而失败了。它尝试重新添加约束而不首先删除它。这是Sequelize的错误还是我对模型的定义错了?

我正在使用以下代码同步表格:

init.db.sync({ alter: true }).then(() => {
    proceed();
}, (error) => {
    console.log(error);
});

1 个答案:

答案 0 :(得分:0)

更新到最新版本的Sequelize之后,问题已解决。遇到相同错误的人可以尝试更新版本。