It starts out ok, but you should not use a pivot for a one-to-many relation, just add the spending_category_id to the transaction.
Laravel model structure for breaking cost into categories
For a side project, I'm creating a small personal budgeting type app, and one of the features is basically an account register, where you can enter a payment to a vendor. Part of this is being able to categorize the payment - either as a whole, or spread across different categories. Say, for instance, that I go to Home Depot, and I buy stuff for my yard, and other stuff for some remodeling work in my house, so I want some to the Landscaping category, and some to Home Repair.
So for my relevant models, I have a Transaction model, and a SpendingCategory model.
Fields are:
Transaction- id, date, amountSpendingCategory- name
So with all that, my issue is this; the best way to break the payment down into multiple categories with an amount. SpendingCategory is obviously just the definition of the category, so I can't have an amount field in it, because the amount will vary every time I use it. As best I can tell I need a third model, something like CategoryAmount with a relationship to Transaction that also has an amount field. So then, my Transaction model would have a categoryAmount relationship:
public function categoryAmount()
{
return $this->hasMany(CategoryAmount::class);
}
and the inverse on CategoryAmount would be
public function transaction()
{
return $this->belongsTo(Transaction::class);
}
For the relationships between CategoryAmount and SpendingCategory, my CategoryAmount model would have:
public function spendingCategory()
{
return $this->belongsTo(SpendingCategory::class);
}
and the inverse on SpendingCategory would be
public function categoryAmount()
{
return $this->hasMany(CategoryAmount::class);
}
So my spending_categories table would have transaction_id and spending_category_id columns, since it belongs to the Transaction and CategoryAmount tables.
Does that sound correct for what I'm trying to do, is is there a better set of relationships to use?
Please or to participate in this conversation.