staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

Deep relationships with pivot #88

Closed kylewallace closed 4 years ago

kylewallace commented 4 years ago

Hello, I am having some trouble traversing some relations & was unable to find my answer in the closed issues, if anyone is able to help? I think it is similar to some other questions but I wish to go a little deeper with the relations.

I've got the following example tables set up (they are just made up table names):

city → company ← service ← employee ← skill

The relations are all standard eloquent belongsTo or HasMany with company being a pivot between city & service using belongsToMany.

I would like to define relationships between employee & city, then go one one step deeper with skill & city as well. Is this possible?

I would also then like to define the inverse of these relationships.

staudenmeir commented 4 years ago

Which directions do the HasMany relationships between Service, Employee and Skill go?

kylewallace commented 4 years ago

Whoops sorry mate, wasn't clear enough.

Service HasMany Employee Employee HasMany Skill

City BelongsToMany Service (and visa versa)

kylewallace commented 4 years ago

I think I might have worked it out. Could I trouble you to have a look at these relationships?

Relationships between city & employee

City.php

/**
 * The employees for the city.
 * 
 * @return \Staudenmeir\EloquentHasManyDeep\HasManyDeep
 */
public function employees()
{
    return $this->hasManyDeep(Employee::class, [Company::class, Service::class], [null, 'id'], [null, 'service_id']);
}

Employee.php

/**
 * The cities for the employee.
 * 
 * @return \Staudenmeir\EloquentHasManyDeep\HasManyDeep
 */
public function cities()
{
    return $this->hasManyDeep(City::class, [Service::class, 'companies'], ['id', null, null], ['service_id', null, null]);
}

Deeper relationships between city and skill

City.php

/**
 * The skills for the city.
 * 
 * @return \Staudenmeir\EloquentHasManyDeep\HasManyDeep
 */
public function skills()
{
    return $this->hasManyDeep(Skill::class, [Company::class, Service::class, Employee::class], [null, 'id', null], [null, 'service_id', null]);
}

Skill.php

/**
 * The cities for the skill.
 * 
 * @return \Staudenmeir\EloquentHasManyDeep\HasManyDeep
 */
public function cities()
{
    return $this->hasManyDeep(City::class, [Employee::class, Service::class, 'companies'], ['id', 'id', null, null], ['employee_id', 'service_id', null, null]);
}
staudenmeir commented 4 years ago

Looks good to me!