To associate and retrieve the siblings (roles and people) for a Project model, you can use a combination of relationships and custom queries. Here's a possible solution:
- Define the relationships in your Project model:
public function roles()
{
return $this->morphToMany(Role::class, 'positionable', 'positions');
}
public function people()
{
return $this->morphToMany(Person::class, 'positionable', 'positions');
}
- To retrieve the roles with the associated people, you can use a custom query with a join:
$test = Project::with(['roles', 'people'])
->join('positions', 'projects.id', '=', 'positions.positionable_id')
->join('roles', 'roles.id', '=', 'positions.role_id')
->join('people', 'people.id', '=', 'positions.person_id')
->get();
- If you want to retrieve the people for each role, you can define a relationship in your Role model:
public function people()
{
return $this->morphToMany(Person::class, 'positionable', 'positions');
}
Then, you can retrieve the roles with their associated people using:
$test = Project::with('roles.people')->get();
- Similarly, if you want to retrieve the roles for each person, you can define a relationship in your Person model:
public function roles()
{
return $this->morphToMany(Role::class, 'positionable', 'positions');
}
Then, you can retrieve the people with their associated roles using:
$test = Project::with('people.roles')->get();
Note: Make sure to replace Role and Person with the actual class names of your Role and Person models.