2016-01-07 125 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);