2016-01-07 126 views
1

我有三種模式和多對多的關係。環境有很多服務。服務有許多ServiceRoles。我想返回給定環境的適用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'); 
    } 
} 

服務模式

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);