【发布时间】:2016-04-12 03:46:45
【问题描述】:
我有三个模型和多对多关系。环境有许多服务。服务有许多 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');
}
}
【问题讨论】:
标签: php mysql laravel eloquent many-to-many