I’m trying to come up with a good database design for this use case
I have a table called expenses
as follows
id
category_id
item_id
Problem
item_id
column wouldn’t make sense if the expenses category is i.e. "Rent"- It would only make sense if the category is i.e. "Food"
I have thought of two different approaches
1st approach:
Make the item_id
column nullable
2nd approach:
Create a separate table called expense_item
with the following columns
expense_id
item_id
And drop the item_id
column from the expenses
table
I’m not sure what approach I should go with or if there’s a better approach. I’m not sure how to handle this case scenario
2
Answers
You could categorize Rent like mint.com does.
For expenses like Rent, that would be the
item_id
and thecategory_id
could beHome
orHome Expenses
. This category could also include items like home improvements, furniture, etc.The following technique is just an extension of your 1st approach. You allow the
item_id
to be NULL, but validate its null or not null value against the category. I presume you have acategories
table, if not you create it as you do in need it anyway. Now create or add a columnitem_required boolean
. Create a trigger that checks the presence or absence ofitem_id
againstitem_required
for the specified category. This results in something like the following: (seedemo here
)The assumption here is that a category either must have an item or cannot have an item. You of course need to adjust the trigger to your exact requirement.
In case it does not yet exist the following is a sample setup for a
categories table
.