[英]Laravel Relationship Pivot table multiple relations
您好需要以某种方式获得这些模型之间的关系
1) 汽车服务 Model
2)主Model
3) 服务 Model
这是我的 pivot 表结构
id, auto_service_id, master_id, service_id
现在我需要为每个 AutoService 获取它的 Masters 和他们提供的服务。
一个 Master 可以属于多个 AutoService,并在每个 AutoService 中提供不同的服务。
同一个 AutoService 中的多个 master 可以提供相同的服务。
如何建立这些模型之间的关系?
您应该有一张 pivot 表autoservice_service
。
在您的服务模型中
public function autoServices(){
$this->belongsToMany('App\AutoService');
}
在你的主 model
public function autoServices(){
$this->hasMany('App\AutoService');
}
在您的汽车服务 model
public function services(){
$this->belongsToMany('App\Service');
}
public function masters(){
$this->belongsTo('App\Master');
}
在 pivot 表中使用service_id
, master_id
, autoservice_id
。 如果你想使用时间戳使用方法withTimestamps()
(fe $this->belongsToMany('App\Master')->withTimestamps();
编辑:如果您想在 Master 和 Service 之间建立关系,其中一个 Master 可以有多个服务,反之亦然,您应该制作另一个 pivot 表master_service
。 在Service
model:
public function masters(){
return $this->belongsToMany('App\Master');
}
在Master
model 中:
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();
另一种解决方法是您可以在 pivot 表中添加另一个外键,然后使用->withPivot('column1', 'column2')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.