Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

postgresql - SQL database relationships: correct implementation of Junction Model in manyToMany relationship?

I have two database tables "Users" and "Transactions" with many to many relationship between them. I have created a Junction Model which will have two foreign key columns (UserId, TransactionId) and will keep track of the associations. The Transaction table has two columns where I keep track of who the sender is and who the recipient is (senderAccount, recipientAccount).

Question 1: since each Transaction belongs to two users which are the sender and recipient, do I also need to specify both senderId and recipientId inside the junction model instead of just userId?

Note: my confusion is from the two foreign key columns(UserId and TransactionId) inside the junction model. I understand that there is only one transaction and you can reference that transaction by its id in the junction model, but each transaction is also owned by two users (sender and recipient) shouldn't we reference both of the users inside the junction model?

Question 2: if my analogy up here is correct, how would you reference both senderId and recipientId inside the junction model?

Question 3: if my analogy up here is incorrect, please help me understand how you would go about referencing both users in the junction model.

Users table

id | username | 
—--+----------+
 1 | ijiej33  |    

Transactions table

id | transactionId | senderAccount | recipientAccount | Amount |
—--+---------------+---------------+------------------+--------+
 1 | ijiej33       |      A        |         B        |   100  |  

userTransaction table (junction model)

userId | TransactionId |
-------+---------------+
       |               |
question from:https://stackoverflow.com/questions/65883976/sql-database-relationships-correct-implementation-of-junction-model-in-manytoma

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I explained as a comment in your question from yesterday, you do not have a many-to-many relationship between transactions and users. You have two many-to-one relationships from transactions to users. You therefore do not need a join table.

Model it thus:

create table users (
  user_id serial primary key,
  user_name text not null unique
);

create table transaction ( 
  transaction_id serial primary key,
  sender_account int not null references users(user_id),
  recipient_account int not null references users(user_id),
  amount numeric
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...