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:
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;
I came up with the following idea to utilize the existing Polymorphic Relationship to handle multiple associations.
First, I changed the schema to this:
Employees
id
NonEmployees
id
Sponsors
id
sponsored_id
sponsored_type
sponsorable_id
sponsorable_type
So, I removed the sponsor_id field from each of the account type tables and added a second polymorphic relationship to the Sponsors table.
I updated the models as follows:
Models/Employee.php & Models/NonEmployee.php
public function sponsorable()
{
return $this->morphOne('Sponsor', 'sponsorable');
}
public function sponsors()
{
return $this->morphMany('Sponsor', 'sponsor');
}
Models/Sponsor.php
public function sponsor()
{
return $this->morphTo();
}
public function sponsorable()
{
return $this->morphTo();
}
Now, because Laravel doesn't support a morphManyThrough() relationship type, you'll notice I changed some of the names of the functions so that it would read a little cleaner when using the relationships since I have to go from one table through an intermediary table and then to a 3rd table to get the information I want.
With this structure, I can do the following:
$employee = Employee::find(2)->sponsorable->sponsor; // Gets employee's sponsored party
$sponsors = $employee->sponsors; // Gets individual that the employee is sponsoring.
foreach ($sponsors as $sponsor)
echo $sponsor->sponsorable->first_name;
$employee->sponsors()->save(new Sponsor()); // New sponsor
$non_employee->sponsors()->save(new Sponsor()); // New sponsor
I can also perform a reverse lookup:
Sponsor::find(1)->sponsor->first_name; // Sponsoring party
Sponsor::find(1)->sponsorable->first_name; // Party being sponsored