2016-10-03 3 views
0

Привет У меня есть три таблицыLaravel Eloquent присоединиться три таблицы имеет много через

организации

id | name 
1 | org1 
2 | org2 

сайт

id | name | organisation_id 
1 | site1 | 1 
2 | site2 | 1 
3 | site3 | 2 

служба

id | name  | site_id 
1 | service1 | 1 
2 | service2 | 1 
3 | service2 | 2 

Здесь я хочу получить все услуги по организации (скажем, 1). я могу получить все сайты организации, как это, но как я могу получить услуги:

$sites = Site::whereHas('organisation', function ($query) { 
    $query->where('id', 1); 
})->get(); 

Модель

organisationModel

public function sites() { 
    return $this->hasMany('App\Site'); 
} 

siteModel

public function organisation(){ 
    return $this->belongsTo('App\Organisation'); 
} 

public function services() { 
    return $this->hasMany('App\Service'); 
} 

ServiceModel

public function site(){ 
    return $this->belongsTo('App\Site'); 
} 

ответ

1

Вы можете получить, как отношения с 'has many through':

организации Модель:

public function services() 
{ 
    return $this->hasManyThrough(Service::class, Site::class, 'organisation_id', 'site_id', 'id'); 
} 

Чтобы получить:

$services = Organisation::find(1)->services; 

Или вы можете получить все услуги с nestedwhereHas:

$services = Service::whereHas('site.organisation', function ($query) { 
    $query->where('organisation.id', 1); 
})->get(); 
+0

отлично, как я пропустил «многое» благодаря – sanu

0

Вы можете получить таким образом:

Site::with('organisation') 
      ->select('id', 'name') 
      ->with(['services' => function ($q) { 
        return $q->select('id', 'name'); 
      }]) 
      ->where('organisation_id', 1) 
      ->get(); 
0

Это может быть достигнуто без whereHas с nested eager loading

$organization=Organization::with('sites','sites.services')->where(['id'=>1])->first(); 
foreach($organization->sites as $site) 
{ 
    foreach($site->services as $service) 
    { 
     print_r($service->name); 
    } 
} 
Смежные вопросы