首页 > 解决方案 > postgresql 事务违反外键约束

问题描述

我有以下nodejs代码(简化):

// tables

CREATE TABLE admins (
    admin_id bigint DEFAULT nextval('admins_seq') NOT NULL,
    username character varying(25) NOT NULL,
    password character varying(150) NOT NULL
);
CREATE TABLE admin_notifications (
    admin_notification_id bigint DEFAULT nextval('admin_notifications_seq') NOT NULL,
    admin_id bigint NOT NULL,
    type character varying(150) NOT NULL
);
ALTER TABLE admin_notifications ADD CONSTRAINT admin_notifications_to_admins_fk FOREIGN KEY (admin_id) REFERENCES admins(admin_id) ON DELETE CASCADE;


await client.query('BEGIN');

// create a new array in the database and return the newly created admin id
const query = 'INSERT INTO admins (username, password) VALUES($1,$2) RETURNING admin_id';
const values = [];
const result = await client.query(query, values);

// insert a welcome notification for the newly created admin
const query2 = 'INSERT INTO admin_notifications (admin_id, type) VALUES ($1,$2)';
const values2 = [result.rows[0].admin_id, 'welcome'];
const result2 = await client.query(query2, values2);

await client.query('COMMIT');

一点解释:我在表 admins 中创建了一个新管理员。创建新管理员时,我想在表 admin_notifications 中插入新的欢迎通知。表 admin_notifications 中的列 admin_id 是表 admins (admin_id) 的外键。

我收到以下错误:

错误:在表“admin_notifications”上插入或更新违反外键约束“admin_notifications_to_admins_fk”

当我忽略交易时,它会起作用吗?!

它与延迟约束有关吗?以及如何在我的代码中处理这个?

标签: postgresqltransactions

解决方案


推荐阅读