我正在尝试使用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',
});
我曾尝试在模型文件中使用引用,但得到了相同的错误
发布于 2021-10-21 08:46:55
在使用NodeJS和Sequelize构建应用程序接口时,我也遇到了这个错误。下面是我是如何解决这个问题的。
错误: SequelizeForeignKeyConstraintError:表"states“上的insert或update违反外键约束"states_country_id_fkey”
从上面的错误中可以看出,状态表需要country_id作为它的foreignKey。这意味着,如果指定的country_id不在country表中,您将无法创建一个州。
解决方案:我建议先在"country“表中设定种子,以确保存在”country_id“表中引用的指定状态。
然后尝试将数据插入到状态表中。这应该可以解决问题。
https://stackoverflow.com/questions/63949324
复制相似问题