Reputation: 835
From my knowledge, if you make many to many relations I always used to use association table
. Nevertheless, now I have requirement from business (not sure if they have db knowledge) to create relationships
between two tables directly. To me that's not possible. They saying that I have to do as follows, so for example what they saying is:
TableA
ID (PK)
refKey
TableB
ID (PK)
refKey
Make many to many between TableA.refKey
and TableB.refKey.
Is something like that possible?? I've tried but postgres yield to create unique
. And.. if I create unique
for any of refKey
from my knowledge it will be 1:M or M:1
. Am I missing something? Nevertheless if you say that's possible please of sample code to initiate such connection based on that particular example.
Upvotes: 0
Views: 708
Reputation: 1270443
You can create a many-to-many relationship with just two tables. This is not a best practice, but it might be practical in some circumstances.
In Postgres, the simplest way is to have an array of ids that references the second table:
create table a (
a_id int generated always as identity,
b_ids[] int
);
Why is this generally a bad idea?
check
constraint.)unnest()
.)a
.In other words, lots of the "built-in" functionality is missing when you do this.
I should note that you can also do this with JSON as well as arrays.
Upvotes: 1
Reputation: 26056
You're right there will only be many-to-one or one-to-many relationships. What you need is a joining table, for example:
create table A_B (
A_id bigint references A,
B_id bigint references B
)
Then you can have as many rows with the same A_id
or B_id
as you want. That results in a many-to-many relationship.
Upvotes: 1