【问题标题】:Laravel 5.1 Eloquent distant relationship with many to many modelsLaravel 5.1 Eloquent 与多对多模型的远距离关系
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-05-25
      • 2013-05-15
      • 2014-09-27
      • 1970-01-01
      • 2016-02-21
      • 2015-12-10
      • 2020-03-27
      • 2019-06-13
      • 2016-02-11
      相关资源
      最近更新 更多