Ad

Laravel 5.1 Eloquent Distant Relationship With Many To Many Models

- 1 answer

I have three models and many-to-many relationships. Environments have many Services. Services have many ServiceRoles. I would like to return the applicable ServiceRoles of a given Environment, but I am unsure of what I may need to define in the Environment model.

In my Controller I have:

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

My MySQL tables and fields are as follows:

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]  

Environment Model

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 Model

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

Answer

You can use the hasManyThrough relationship to query for models through an intermediary model.

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

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

You should be able to query the an environment model for all of it's service roles.

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

// Should output a collection of ServiceRole models
dd($environment->serviceRoles);
Ad
source: stackoverflow.com
Ad