【问题标题】:Laravel 5.1 Distant relationships with one-to-many and many-to-many modelsLaravel 5.1 与一对多和多对多模型的远距离关系
【发布时间】:2016-05-25 00:50:40
【问题描述】:

我配置了 5 个模型。客户、环境、对象、服务角色和服务。我已经在每个模型中建立了适当的雄辩关系。

客户有许多环境。

//Customer Model    
public function environments()
{
return $this->hasMany('App\Environment');
}

环境属于一个客户。
环境属于许多对象。

//Environment Model   
public function customer()
{
    return $this->belongsTo('App\Customer');
}

public function objects()
{
    return $this->belongsToMany('App\Object');
}  

对象属于许多环境。
对象属于许多 ServiceRoles。

//Object Model
public function environments()
{
    return $this->belongsToMany('App\Environment');
}

public function serviceRoles()
{
    return $this->belongsToMany('App\ServiceRole');
}

ServiceRoles 属于许多对象。
ServiceRoles 属于一个 Service。

//ServiceRole Model
public function objects()
{
    return $this->belongsToMany('App\Object');
}

public function service()
{
    return $this->belongsTo('App\Service');
}

服务属于许多服务角色。

public function serviceRoles()
{
    return $this->hasMany('App\ServiceRole');
}

--SQL--
客户:id、名称
对象:id、名称
环境: id、name、customer_id
environment_object:id、environment_id、object_id
service_roles:id、name、service_id
object_service_role : id, object_id, service_role_id
服务: id, name

1) 检索与客户关联的所有对象(跨所有相关环境)的最简单方法是什么?

想做类似的事情:$customer->objects

2) 我怎样才能检索与客户关联的对象的所有服务,因为每个对象都有一个映射到服务的 ServiceRole。

想做类似的事情:$customer->services

【问题讨论】:

  • 抱歉,我添加了模型并稍微修改了我的第二个问题以反映我错过的另一个模型。谢谢

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


【解决方案1】:

最好发布你所有的关系。但如果你说你已经适当地建立了你的关系,那么以下应该可以工作。

 1. Customer::with('environments.objects')->get();

但如果它只是为客户做的

 Custmer::with('environments.objects')->find($id);


 2. Customer::with('environments.objects.roles')->get();

仅供客户使用

 Customer::with('environments.objects.roles')->find($id);

【讨论】:

  • 这似乎检索嵌套集合,我必须循环遍历。有没有办法只检索“对象”和“服务”?我还添加了我的模型并澄清了我的第二个问题,因为我对整体数据库设计不太清楚。谢谢!
猜你喜欢
  • 2016-04-12
  • 2016-03-02
  • 2016-02-21
  • 1970-01-01
  • 2016-06-11
  • 1970-01-01
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多