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

时间:2018-07-07 09:26:15

标签: mysql sequelize.js

我有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;
};

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

执行(默认):如果不存在admin_usersid INTEGER auto_increment,name VARCHAR(255),email VARCHAR(255)NOT NULL UNIQUE,则创建表user_name VARCHAR(255)NOT NULL唯一,createdAt DATETIME NOT NULL,updatedAt DATETIME NOT NULL,主键(id))ENGINE = InnoDB; 执行中(默认):从admin_usersmilkman_prod1显示索引 执行(默认):如果不存在,则创建表admin_accountsadmin_user_id INTEGER,password VARCHAR(255),createdAt DATETIME NOT NULL,updatedAt DATETIME NOT NULL ,主键(admin_user_id),外键(admin_user_id)参考admin_usersid)在更新级联上删除设置为空)ENGINE = InnoDB; 未处理的拒绝SequelizeDatabaseError:无法添加外键约束

1 个答案:

答案 0 :(得分:1)

请尝试使用以下代码:

    '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;
    };