ninjacoder
ninjacoder

Reputation: 293

Several entities having a one to many relation with one specific entity

Imagine a scenario where we have companies, bank accounts, and customers. Both companies and customers can have many bank accounts but a bank account can belong to either only one customer or one company. I'd like to know the best way to design such a database that will not involve complicated queries or business logic especially when it comes to the point where we need to delete a bank account from the database.

One solution I've seen is to reference the id's of bank accounts as a JSON string array on either companies or customers like this:

In customer or company
======================
id    name  bank_account
1     Bob   [2,3,4,5]

It's not a bad solution but I'm wondering if there's a better way to do this.

NB: I'm building the application using Symfony 2.7.5 and therefore using the Doctrine ORM library.

Upvotes: 1

Views: 64

Answers (1)

Carlos Granados
Carlos Granados

Reputation: 11351

One way to handle this is to have both companies and customers inherit from a common ancestor, say users (take a look at doctrine inheritance). Then there would be a one to many relationship between users and bank accounts, which is really easy to implement and would take care of all your dependencies.

Upvotes: 1

Related Questions