Laravel 5.1与许多模型雄辩的远距离关系

时间:2016-01-07 16:37:12

标签: php mysql laravel eloquent many-to-many

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

在我的控制器中我有:

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

1 个答案:

答案 0 :(得分:2)

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