SequelizeForeignKeyConstraintError:对表“ states”进行插入或更新违反了外键约束“ states_country_id_fkey”

时间:2020-09-18 04:26:20

标签: node.js postgresql sequelize.js

我正在尝试使用Sequelize Sync功能插入数据。但我得到这个错误。问题是有时候数据成功输入而有时候却不成功

错误

config/sequelize.js:295
SequelizeForeignKeyConstraintError: insert or update on table "states" violates foreign key 
constraint "states_country_id_fkey"
at Query.formatError 
(d:\projects\petrolpump\node_modules\sequelize\lib\dialects\postgres\query.js:315:16)
at Query.run (d:\projects\petrolpump\node_modules\sequelize\lib\dialects\postgres\query.js:87:18)
at processTicksAndRejections (internal/process/task_queues.js:97:5) {name: 
'SequelizeForeignKeyConstraintError', parent: error: insert or update on table "states" viol…ign key 
constraint "states_country_id_fkey"
…, original: error: insert or update on table "states" vio…gn key constraint "states_country_id_fkey"
…, sql: 'INSERT INTO "states" ("id","name","country_id"… 
untry_id","is_active","createdAt","updatedAt";', parameters: Array(5), …} 

这是查询

sync function initial() {
try {
var country = await db.country.findOne({ where: { name: 'India' } });
if (!country) {
  db.country.create({
    name: "U.S.",
    is_active: "true"
  });
}

var state = await db.state.findOne({ where: { name: 'Gujarat' } });
if (!state) {
await  db.state.create({
    name: "California",
    country_id: "1",
    is_active: "true"
  });
 }
} catch (e) {
   console.log(e)
  }
}

db.sequelize.sync({ force: true }).then(() => {
  console.log("Drop and re-sync db.");
  initial();
});

这是阴谋

db.state.hasMany(db.city, {
  foreignKey: 'state_id'
});

db.country.hasMany(db.state, {
  foreignKey: 'country_id',
});

我尝试在模型文件中使用参考,但出现了错误的错误

1 个答案:

答案 0 :(得分:0)

我能够解决该错误。 idon不知道是因为版本错误,但是当我安装对我有用的旧版本时是5.21.3