postgresql - 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”
当我忽略交易时,它会起作用吗?!
它与延迟约束有关吗?以及如何在我的代码中处理这个?
解决方案
推荐阅读
- wpf - WPF - 文本框的 SuggestAppend
- powershell - PowerShell Remove-Item - 字符串后的通配符?
- python - sqlalchemy 可以添加两个特定列不能同时为 None 的字段级规则吗?
- mysql - 更改 apache 的端口后,mysql 在 xampp 中运行正常,但 myphpadmin 显示这些错误
- variables - 我们可以在 gitlab-ci.yml 中使用动态作业名称吗?
- c# - 从另一个窗口句柄获取实时消息
- python - Rethinkdb: Changefeed -> 如何查看/返回 2 个字段?
- python - 如何正确运行 pyqt5 应用程序?
- jakarta-ee - 修改 Web 服务调用中的 HTTP 标头
- excel - 删除第 n 个字符后的所有字符