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