I’m working on a personal project for timekeeping on various projects, but I’m not sure of the best way to structure my database.
A simplified breakdown of the structure is as follows:
- Each client can have multiple reports.
- Each report can have multiple line items.
- Each line item can have multiple time records.
There will ultimately be more relationships, but that’s the basis of the application. As you can see, each item is related to the item beneath it in a one-to-many relationship.
My question is, should I relate each table to each “parent” table above it? Something like this:
clients
id
reports
id
client_id
line_items
id
report_id
client_id
time_records
id
report_id
line_item_id
client_id
And as it cascaded down, there would be more and more foreign keys added to each new table.
My initial reaction is that this is not the correct way to do it, but I would love to get some second(and third!) opinions.
The advantage of the way you’re doing it is that you could check all time records for, say, a specific client id without needing a join. But really, it isn’t necessary. All you need is to store a reference back up one “level” so to speak. Here are some examples from the “client” perspective:
To get a specific client’s reports: (simple; same as current schema you suggest)
To get a specific client’s line items: (new schema; don’t need “client_id” in table)
To get a specific client’s time entries: (new schema; don’t need “client_id” or “report_id” in table)
So, the revised schema would be:
EDIT:
Additionally, I would consider using views to simplify the queries (I assume you’ll use them often), definitely creating indexes on the join columns, and utilizing foreign key references for normalization (InnoDB only).