2016-01-07 4 views
1

У меня есть три модели и отношения «многие ко многим». В средах есть много Услуг. У служб много сервисов. Я хотел бы вернуть применимые ServiceRoles данной среды, но я не уверен, что мне может понадобиться определить в модели Environment.Laravel 5.1 Яркие удаленные отношения со многими из многих моделей

В моем контроллере у меня есть:

public function getServiceRoles($id) 
{ 
    $environment = Environment::find($id); 
    $serviceRoles = $environment->serviceRoles; 
} 

Мои MySQL таблицы и поля следующим образом:

environments [id | name] 
services [id | name] 
service_roles [id | name] 
environment_service [id | environment_id | service_id] 
service_service_roles [id | service_id | service_role_id] 

окружающей среды Модель

class Environment extends Model 
{ 
    public function services() 
    { 
     return $this->belongsToMany('App\Service'); 
    } 
} 

Service Model

class Service extends Model 
{ 
    public function environments() 
    { 
     return $this->belongsToMany('App\Environment'); 
    } 

    public function serviceRoles() 
    { 
     return $this->belongsToMany('App\ServiceRole'); 
    } 
} 

ServiceRole Модель

class ServiceRole extends Model 
{ 
    public function services() 
    { 
     return $this->belongsToMany('App\Service'); 
    } 
} 

ответ

2

Вы можете использовать hasManyThrough отношения для запроса моделей через посредника модели.

class Environment extends Model 
{ 
    public function services() 
    { 
     return $this->belongsToMany('App\Service'); 
    } 

    public function serviceRoles() 
    { 
     return $this->hasManyThrough('App\ServiceRoles', 'App\Service'); 
    } 
} 

Вы должны иметь возможность запрашивать модель среды для всех ее служебных ролей.

$environment = Environment::with('serviceRoles')->first(); 

// Should output a collection of ServiceRole models 
dd($environment->serviceRoles); 
Смежные вопросы