Laravel 5.1 Eloquent 与多对多模型的远距离关系

Laravel 5.1 Eloquent distant relationship with many to many models

我有三个模型和多对多关系。环境有很多服务。服务有很多 ServiceRoles。我想 return 给定环境的适用 ServiceRoles,但我不确定我可能需要在环境模型中定义什么。

在我的控制器中我有:

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

服务角色模型

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

您可以使用 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);