未处理的拒绝SequelizeDatabaseError:无法添加外键约束

我有2个表:admin_user和admin_account .

const Sequelize = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  var admin_user = sequelize.define('admin_user', {
    id: {
      autoIncrement: true,
      type: Sequelize.INTEGER,
      primaryKey: true
    },
    name: {
      type: Sequelize.STRING
    },
    email: {
      type: Sequelize.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isEmail: true,
      }
    },
    user_name:{
      type: Sequelize.STRING,
      allowNull: false,
      unique: true
    }
  });

  admin_user.associate = (models) =>{
    admin_user.hasOne(models.admin_account, { foreignKey: 'admin_user_id' });
  };

  return admin_user;
};


'use strict';
const Sequelize = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  var admin_account = sequelize.define('admin_account', {
    admin_user_id:{
      type: Sequelize.INTEGER,
      primaryKey: true
    },
    password: {
      type: Sequelize.STRING
    }
  });
  return admin_account;
};

并在创建表时出现此错误:

执行(默认):CREATE TABLE IF NOT EXISTS admin_usersid INTEGER auto_increment, name VARCHAR(255), email VARCHAR(255)NOT NULL UNIQUE, user_name VARCHAR(255)NOT NULL UNIQUE, createdAt DATETIME NOT NULL, updatedAt DATETIME NOT NULL, PRIMARY KEY( id ))ENGINE = InnoDB;执行(默认):SHOW INDEX FROM admin_users FROM milkman_prod1 执行(默认):CREATE TABLE IF NOT NOT EXISTS admin_accountsadmin_user_id INTEGER, password VARCHAR(255), createdAt DATETIME NOT NULL, updatedAt DATETIME NOT NULL,PRIMARY KEY( admin_user_id ),FOREIGN KEY ( admin_user_id )REFERENCES admin_usersid )ON DELETE SET NULL UPDATE CASCADE)ENGINE = InnoDB; Unhandled rejection SequelizeDatabaseError: Cannot add foreign key constraint

回答(1)

2 years ago

请尝试使用此代码:

'use strict';
    const Sequelize = require('sequelize');
    module.exports = (sequelize, DataTypes) => {
      var admin_account = sequelize.define('admin_user', {
        admin_user_id:{
          type: Sequelize.INTEGER,
          primaryKey: true
        },
        password: {
          type: Sequelize.STRING
        }
      });
admin_account.associate = (models) =>{
    admin_account.belongsTo(models.admin_user);
  };
      return admin_account;
    };