I’m building a web-app where users can keep track of who owes whom money.
I have users and debts.
Given a user I want to be able to find out all the debts to other users, and all the loans to other users.
Given a debt I want to be able to find out who the debtor and lender are.
The asker of this question ran into a similar situation, but I don’t belive our situations similar enough to warrant just using the top answer:
https://stackoverflow.com/questions/4729725/how-do-i-do-two-has-many-belongs-to-relationships-between-two-models
Taken from that question, the three paterns sugested there are
- well specified associations
- single table inheritance
- polymorphic association
What pattern should I use in my situation? One of these three, or is there an even more appropriate one?
0
I would advice a simpler solution. 2 one-to-many relations, let me explain:
One debt table with 2 user_ids as debitor_id
and creditor_id
.
like that a user has many loans and many debts, but each debt has only one creditor and one debitor.
Both your models and querying are straightforward, and the cases you have mentioned seem to be covered.
NB: while it is possible to for the same 2 users to have multiple loan and debt records, I would recommend against this by validating the uniqueness of the debitor_id, creditor_id combination (if that functionality is not required) in order to simplify querying and having cleaner ORM attributes.
4
Looks like a straightforward one-many problem
I would approach it as
User 1 – * Debt
User 1 – * Loan
Then all you need are the tables User
, Debt
and Loan
. The relationships are bi-directional.
From your pick list this is “well-specified associations”. I don’t think inheritance or polymorphism is required in this situation.
4