Reputation: 255
I have a Laravel 5.4 project where these are some of the models: Client, Owner, Employee, Bank (actually it is Bank Account but I have chosen Bank for easy naming conventions in building relationship with foreign keys).
What is the best way to build the tables and the relationship. I have thought of the following:
Now when building Bank Blade View Forms (Create/Update) should I have a drop-menu e.g. belongs_to field having Client, Owner, Employee as options - then accordingly, I can filter out One of the three tables to choose id of the holder of bank account to allocate it.
each Bank will have only active foreign key - at a time - for one of the 3 tables e.g. client_id = 36 and the other two are always 0 in their value e.g. owner_id = 0 & employee_id = 0)
Is this is the best way in building the relationship or there is another better way? Please provide the blade view form for banks if possible.
Upvotes: 2
Views: 992
Reputation: 6319
This relation would suit a Polymorphic Relation.
You can have your Bank accounts apply to one of the other relations like this
class BankAccount extends Model
{
public function accountOwner()
{
return $this->morphTo();
}
}
class Client extends Model
{
public function bankAccount()
{
return $this->morphMany('BankAccount', 'bankAccount');
}
}
Note that I've used the name BankAccount
because I really recommend using a name that specifically mention what it represents. In the future you or some other developer might get confused about "Bank" actually meaning "Bank Account". And you should also consider what you would do if you decided to add Banks to your model, so each account belongs to a "Bank".
The obvious disadvantage of polymorphic relations is the fact that you cannot have physical foreign keys on the database tables.
Upvotes: 0
Reputation: 2126
Looks like a great candidate for a polymorphic relationship.
Your table structure will look something like:
The main differences from your proposed structure is the fact we do not specify the bank in the clients, owners or employees table (since they can have multiple). Instead we specify what type of user the bank belongs to using bankable_id and bankable_type.
Then in each of your three user models; clients, owners and employees, you have the following (it may be best to put this in a trait):
public function banks()
{
return $this->morphMany('App\Bank', 'bankable');
}
In your banks model, you can then have:
public function bankable()
{
return $this->morphTo();
}
Which will return the user (a client, owners or employees model) that owns the bank.
Upvotes: 1