I'm trying to use an intermediary table to signify a sponsorship relationship between two different user tables (Employee & Non-Employee) with the following requirements:
- A sponsor can be either an Employee or Non-Employee.
- An Employee/Non-Employee can belong to only one sponsor.
- An Employee can have many sponsors.
I noticed that Polymorphic Relationships for Laravel only support single associations. Typically they use the intermediary table in the relationship to prevent having to create multiple tables with the same signature. In my case, I need to polymorph both sides of the relationship since at any point I could have the sponsor/sponsored person belong to either table. I'm not sure if I'm going about this right, sort of stumped at the moment.
Here's what I currently have:
Employees
id
sponsor_id
NonEmployees
id
sponsor_id
Sponsors
id
sponsorable_id
sponsorable_type
Next, I setup the following models:
Models/Employee.php
public function sponsors() {
return $this->morphMany('Sponsor', 'sponsorable');
}
Models/NonEmployee.php
public function sponsors() {
return $this->morphMany('Sponsor', 'sponsorable');
}
Models/Sponsor.php
public function sponsorable() {
return $this->morphTo();
}
With this setup, I was able to perform general lookup queries against the Sponsors table and then reverse engineer them to retrieve the name of the sponsor.
Sponsor::with('sponsorable')->get();
Sponsor::find(1)->sponsorable;