Reputation: 13128
Basically I'll be having 3 tables that have relation. They are: users
, departments
and company
.
The issue I have is this:
company
can have many departmentsdepartment
can only be attached to one companyuser
can only be part of one companyuser
can be part of many departmentsThis is essentially what the table relation would look like:
____________________
| | | | |
| | | | |
-------- -------------- -----------
| user | | department | | company |
-------- -------------- -----------
| | | | | | | |
| | | | | | | |
| ___________________ |
| |
| |
| |
_______________________________________
The above multiple |
lines show an option, so the "company" above has 4 departments and so on.
Now my question is this, How should I structure the relation tables?
Should I have user_departments
, user_company
and company_departments
tables?
That would essentially look like this:
--------------------
| user_departments |
--------------------------------
| id | user_id | department_id |
--------------------------------
----------------
| user_company |
-----------------------------
| id | user_id | company_id |
-----------------------------
-----------------------
| company_departments |
-----------------------------------
| id | company_id | department_id |
-----------------------------------
Or are there any other alternatives for me to consider/implement instead of the path I'm going as it seems it'll just keep growing complex?
Upvotes: 1
Views: 55
Reputation: 421
Here is the layout in the format you used:
---------
| users |
--------------------------------
| id | name | company_id | ... |
--------------------------------
-----------
| company |
-------------------
| id | name | ... |
-------------------
-----------
| departments |
--------------------------------
| id | name | company_id | ... |
--------------------------------
--------------------
| user_departments |
--------------------------------
| id | user_id | department_id |
--------------------------------
Upvotes: 2
Reputation: 15951
You are essentially making redundant relationships. You should have no need for a company_departments, company_id will just be a field of the departments table to reference the company a department is a part of. Likewise, you won't need a user_company table, but you will need the user_departments one; that is due to the user-department relationship actually being many-to-many.
With the example you've given, you should only need four tables.
company: company_id, other company info (such as name)
department: department_id, company_id (referencing the company record), other department info
user: user_id, company_id (referencing the company record), other user info
user_departments: user_id, department_id, perhaps information such as user's role in department, or if you want historical data preserved dates assigned to and removed from department
Upvotes: 3