怎么修?未处理的拒绝SequelizeForeignKeyConstraintError:对表“ x”的插入或更新违反了外键约束“ y_fkey”

时间:2020-06-08 02:47:48

标签: node.js postgresql sequelize.js

当我尝试POST /在数据库中创建新联系人时,显示此错误。这是错误Unhandled rejection SequelizeForeignKeyConstraintError: insert or update on table "contacts" violates foreign key constraint "org_name_fkey"。以下是模型,有人知道如何解决此问题吗?所有其他字段POST都很好,只有在尝试添加org_name时才可以。如果我没有在org_name中包括POST,那么所有内容都存储在postgres数据库中。

联系方式

module.exports = (sequelize, DataTypes) => {
  const Contacts = sequelize.define('contact', {
      contact_id: {
        type: Sequelize.INTEGER,
        field: 'contact_id',
        primaryKey: 'true'
      },
      first_name: {
        type: Sequelize.STRING,
        field: 'first_name'
      },
      last_name: {
        type: Sequelize.STRING,
        field: 'last_name'
      },
      contact_type_id: {
        type: Sequelize.STRING,
        references: {
          model: 'contact_type',
          key: 'contact_type_id'
        }
      },
      org_name: {
        type: Sequelize.STRING,
        references: {
          model: 'org',
          key: 'org_name'
        }
      }
    },
    {
      tableName: 'contacts',
    }
  );

  Contacts.associate = (models) => {
    Contacts.belongsTo(models.contact_type, {foreignKey: 'contact_type_id'});
    Contacts.belongsTo(models.org, {foreignKey: 'org_name'});
  };

  return Contacts;
};

联系人类型模型

module.exports = (sequelize, DataTypes) => {
  const ContactType = sequelize.define('contact_type', {
      // attributes
      contact_type_id: {
        type: Sequelize.STRING,
        field: 'contact_type_id'
      },
      updated_at: {
        type: Sequelize.DATE,
        field: 'updated_at'        
      },
      created_at: {
        type: Sequelize.DATE,
        field: 'created_at'
      }
    },
  );

  ContactType.associate = (models) => {
    ContactType.hasOne(models.contact, {foreignKey: 'contact_id'});
  };

  return ContactType;
};

组织模型

module.exports = (sequelize, DataTypes) => {
  const Org = sequelize.define('org', {
      org_name: {
        type: Sequelize.STRING,
        field: 'org_name',
        primaryKey: 'true'
      },
      org_type_id: {
        type: Sequelize.STRING,
        field: 'org_type_id'
      },
      website: {
        type: Sequelize.STRING,
        field: 'website'
      }
    },
  );

  Org.associate = (models) => {
    Org.hasMany(models.contact, {foreignKey: 'contact_id'});
  };

  return Org;
};

1 个答案:

答案 0 :(得分:1)

该错误告诉您的是,无论您传递到POST请求中的org_name在数据库中没有对应的Org记录。即您正在创建一个在ABC Corp工作的人,但尚未将ABC Corp添加到您的组织中。您必须先创建组织,然后再创建联系人来解决此问题。

您没有给出导致错误的确切请求。这将有助于跟踪您的问题。同样,您应该在POST之前查询数据库以查找Org表的状态。也许您忘记了在组织实例上调用save