php - Laravel 5.1 Eloquent distant relationship with many to many models -


i have 3 models , many-to-many relationships. environments have many services. services have many serviceroles. return applicable serviceroles of given environment, unsure of may need define in environment model.

in controller have:

public function getserviceroles($id) {       $environment = environment::find($id);     $serviceroles = $environment->serviceroles; } 

my mysql tables , fields 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');     } } 

you can use hasmanythrough relationship query models through 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 able query environment model of it's service roles.

$environment = environment::with('serviceroles')->first();  // should output collection of servicerole models dd($environment->serviceroles); 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

css - Can I use the :after pseudo-element on an input field? -