代码之家  ›  专栏  ›  技术社区  ›  Sameer

未处理的拒绝SequelizeForeignKeyConstraintError:在表上插入或更新

  •  0
  • Sameer  · 技术社区  · 7 年前

    我的迁移代码:

    module.exports = {
     up(queryInterface, Sequelize) {
       queryInterface.showAllSchemas({
         options: {},
       }).then((data) => {
         data.forEach(schema => queryInterface.addColumn({
           tableName: 'visitors',
           schema, // dynamic schemas coming from loop
         }, 'purposeId', {
           type: Sequelize.INTEGER,
           references: {
             model: 'purposes', // name of Target model
             key: 'id', // key in Target model that we're referencing
           },
         }));
       });
     },
    };
    

    迁移成功完成,我的“访问者”表中也有一个purposeId列。

    但如果我在“访客”表中执行crud操作,我会得到以下错误:

    注意:我使用的是postgres。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Sameer    7 年前

    实际上,我使用约束解决了这个问题:false。

    我从迁移中删除了该引用。

    module.exports = {
     up(queryInterface, Sequelize) {
       queryInterface.showAllSchemas({
         options: {},
       }).then((data) => {
         data.forEach(schema => queryInterface.addColumn({
           tableName: 'visitors',
           schema,
         }, 'purposeId', {
           type: Sequelize.INTEGER,
         }));
       });
     },
    
     down(queryInterface, Sequelize) {
       queryInterface.showAllSchemas({
         options: {},
       }).then((data) => {
         data.forEach(schema => queryInterface.removeColumn({
           tableName: 'visitors',
           schema,
         }, 'purposeId', {
           type: Sequelize.INTEGER,
         }));
       });
     },
    };
    

    在我的Sequelize模型中:

    Visitor.belongsTo(Purpose, { constraints: false });