简体   繁体   中英

How can I automatically add a foreign key to a table on select which is stored in an associated other?

I have a database with some tables among which these 3:

organizations
    organization_id PK
teams
    team_id PK
    team_organization_id FK
users
    user_id PK
teams_users
    tu_id PK
    tu_team_id FK
    tu_user_id FK

So:

  • Team belongs to Organization
  • Organization has many Teams
  • User has and belongs to many Teams
  • Team has and belongs to many Users

And, consequently User has to belong to an Unique Organization. When I select some users, I would want to know (always) to which organization it depends.

What is the best way to deal with this ?

I think for now that perfect solution would be if I could get the organization_id called for example user_organization_id in my all select results on users.

Am I true on this point ? How to do that correctly ?

My database runs on PostgreSQL (9.3).

When I select some users, I would want to know (always) to which organization it depends.

Use joins:

SELECT u.*, t.team_organization_id AS organization_id
FROM   users       u
JOIN   teams_users tu ON tu_user_id = u.user_id;
JOIN   teams       t  ON t.team_id = tu.tu_team_id
WHERE  tu_user_id = $user_id;

To get that automatically , you could create a VIEW encapsulating the query:

CREATE VIEW usr_org As
<query from above>

Then instead of SELECT * FROM users , use:

SELECT * FROM usr_org;

More about views in the manual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM