首页 > 解决方案 > Laravel 关系数据透视表多重关系

问题描述

您好需要以某种方式获得这些模型之间的关系

1) 自动服务模型

2) 主模型

3) 服务模式

这是我的数据透视表结构

id, auto_service_id, master_id, service_id

现在我需要为每个 AutoService 获取它的 Masters 和他们提供的服务。

一个 Master 可以属于多个 AutoService,并在每个 AutoService 中提供不同的服务。

同一个 AutoService 中的多个 master 可以提供相同的服务。

如何建立这些模型之间的关系?

标签: laravelmodelrelation

解决方案


你应该有一个数据透视表autoservice_service

在您的服务模型中

public function autoServices(){
  $this->belongsToMany('App\AutoService');
}

在您的主模型中

public function autoServices(){
  $this->hasMany('App\AutoService');
}

在您的 AutoService 模型中

public function services(){
  $this->belongsToMany('App\Service');
}
public function masters(){
  $this->belongsTo('App\Master');
}

在数据透视表中使用 then service_id, master_id, autoservice_id. 如果你想使用时间戳使用方法withTimestamps()(fe$this->belongsToMany('App\Master')->withTimestamps();

编辑:如果您想在 Master 和 Service 之间建立关系,其中一个 Master 可以有多个服务,反之亦然,您应该制作另一个 pivot table master_service。在Service模型中:

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

Master模型中:

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

现在你可以检查主人做了什么,例子

1) Services of master
App\Master::find($id)->services();
2) Which masters do service
App\Service::find($id)->masters();

另一种解决方法是您可以在数据透视表中添加另一个外键,然后使用->withPivot('column1', 'column2').


推荐阅读