[英]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.