php - laravel eloquent relation 3 models -
i have laravel 5.4 project these of models: client, owner, employee, bank (actually bank account have chosen bank easy naming conventions in building relationship foreign keys).
now here facts:
- each client can have many banks (bank accounts).
- each owner can have many banks (bank accounts).
- each employees can have many banks (bank accounts).
- each bank (account) can have 1 [either client or owner or employee]
what best way build tables , relationship. have thought of following:
tables:
- clients: id, bank_id, other fields...
- owners: id, bank_id, other fields...
- employees: id, bank_id, other fields...
- banks: id, client_id, owner_id, employee_id, other fields...
model relationships
- client hasmany banks , bank belogsto client [done instructed laravel]
- owner hasmany banks , bank belogsto owner
- employee hasmany banks , bank belogsto employee
now when building bank blade view forms (create/update) should have drop-menu e.g. belongs_to field having client, owner, employee options - accordingly, can filter out 1 of 3 tables choose id of holder of bank account allocate it.
disadvantage:
each bank have active foreign key - @ time - 1 of 3 tables e.g. client_id = 36 , other 2 0 in value e.g. owner_id = 0 & employee_id = 0)
is best way in building relationship or there better way? please provide blade view form banks if possible.
looks great candidate polymorphic relationship.
your table structure like:
- clients: id, other fields...
- owners: id, other fields...
- employees: id, other fields...
- banks: id, bankable_id, bankable_type, other fields...
the main differences proposed structure fact not specify bank in clients, owners or employees table (since can have multiple). instead specify type of user bank belongs using bankable_id , bankable_type.
then in each of 3 user models; clients, owners , employees, have following (it may best put in trait):
public function banks() { return $this->morphmany('app\bank', 'bankable'); }
in banks model, can have:
public function bankable() { return $this->morphto(); }
which return user (a client, owners or employees model) owns bank.
Comments
Post a Comment