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

Unhandled rejection SequelizeDatabaseError: Cannot add foreign key constraint

我有2个表:admin_user和admin_account。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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_users(id 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 EXISTS admin_accounts(admin_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_users(id)ON DELETE SET NULL UPDATE CASCADE)ENGINE = InnoDB;
未处理的拒绝SequelizeDatabaseError:无法添加外键约束


请尝试使用此代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    '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;
    };