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

Posted

技术标签:

【中文标题】未处理的拒绝 SequelizeDatabaseError:无法添加外键约束【英文标题】:Unhandled rejection SequelizeDatabaseError: Cannot add foreign key constraint 【发布时间】:2018-12-15 17:36:14 【问题描述】:

我有 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_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, 主键 (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 ON UPDATE CASCADE) ENGINE=InnoDB; 未处理的拒绝 SequelizeDatabaseError: 无法添加外键约束

【问题讨论】:

【参考方案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;
    ;

【讨论】:

谢谢里亚朱尔。它将消除错误,但不会在表中输入任何内容。我想出了另一个解决方案: admin_user.associate = (models) => admin_user.hasOne(models.admin_account, foreignKey: name: 'admin_user_id', allowNull: false , onDelete: 'restrict', onUpdate: 'restrict ' ); ;

以上是关于未处理的拒绝 SequelizeDatabaseError:无法添加外键约束的主要内容,如果未能解决你的问题,请参考以下文章

可能未处理的承诺拒绝未定义不是一个函数

条纹元素抛出“未处理的承诺拒绝”

未处理的拒绝 SequelizeDatabaseError: 未选择数据库

处理快递申请中未处理的承诺拒绝

反应本机中未处理的承诺拒绝错误?

未处理的拒绝 SequelizeEagerLoadingError:未关联,并且无法读取未定义的属性“getTableName”