node.js - SequelizeForeignKeyConstraintError : insert or update on table "states" violates foreign key constraint "states_country_id_fkey"

标签 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',
});
我曾尝试在模型文件中使用引用,但出现了理智的错误

最佳答案

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

关于node.js - SequelizeForeignKeyConstraintError : insert or update on table "states" violates foreign key constraint "states_country_id_fkey",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63949324/

相关文章:

node.js - 如何将标记区域转换为 PostgreSQL 查询?

postgresql - Postgres - 选择日期列值在另一行值范围内的所有行?

sequelize.js - 无服务器功能因 Sequelize 而挂起?

bash - PostgreSQL 命令来自 bash 脚本

mysql - Sequelize 不支持 MySQL 8 身份验证协议(protocol),我不知道如何更改此协议(protocol)

javascript - 从客户端传递referer并在node.js中获取headers.referer

javascript - 如何将公共(public)文件夹从src复制到dist文件夹

javascript - 为什么我继承的静态属性没有值?

node.js - 调用静态函数返回 'Is not a function'

postgresql - 如何在 Bookshelf 中将 LIKE 与日期列一起使用?