1

I have complex eloquent relationship.

company
-id
-name

company_courts
-id
-company_id
-name

company_sports
-company_court_id
-sports_id

sports
-id
-name

Company can have many courts. Courts can have many sports

I want to get all sports belonging to court in one company

I tried to solve this using hasManyThrough but did not work..

return $this->hasManyThrough(Sports::class,CompanyCourts::class,"","","id","id");
Rwd
  • 34,180
  • 6
  • 64
  • 78
Jaeyoung Heo
  • 87
  • 1
  • 11
  • Which model did you add the `hasManyThrough` relationship to? Please can you show the relationship methods you have for all of the models mentioned in your question. – Rwd Mar 25 '19 at 07:07
  • I feel obligated to ask how it "doesn't work"? What result are you currently getting? – Haem Mar 25 '19 at 07:28

2 Answers2

0

Try the below query

Sport::whereHas('companySport', function($query) use ($yourCompanyId){
   $query->has('companyCourt'. function($q) use ($yourCompanyId){
      $q->has('company', function($q2) use ($yourCompanyId){
        $q2->where('company_id', $yourCompanyId)
      })
   })
})
Sandeep Sudhakaran
  • 1,072
  • 2
  • 9
  • 22
0

Laravel has no native support for a direct relationship.

I've created a package for cases like this: https://github.com/staudenmeir/eloquent-has-many-deep

class Company extends Model
{
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function sports()
    {
        return $this->hasManyDeep(
            Sports::class, [CompanyCourts::class, 'company_sports'],
            [null, 'company_court_id']
        );
    }
}
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109