'I have two tables whose foreign refer to each other, how to persist them? [duplicate]
I have two tables, whose foreign refer to each other, I learned from one article that insert script on tables won't work without deferrable in such a scenario, but I am surprised how the same is being achieved in the spring application without deferrable on table structure.
Please refer to the links below: https://www.alibabacloud.com/blog/postgresql-deferrable-constraints-unique-primary-key-foreign-key-and-exclude_597717#:~:text=If%20a%20constraint%20is%20deferrable,the%20end%20of%20the%20transaction.
Solution 1:[1]
In Postgres, non-deferrable constraints are checked after each command. So insert mutually referencing rows in a single command: CTEs are considered to be part of single command.
WITH ins1 AS (
INSERT INTO tbl1(tbl1_id, tbl2_id) VALUES(2, 3)
)
INSERT INTO tbl2(tbl2_id, tbl1_id) VALUES(3, 2);
(Deferable constraints allow to postpone the check until the end of the transaction. But they are more expensive.)
See:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Erwin Brandstetter |
