laravel - Laravel 关系数据透视表多重关系
问题描述
您好需要以某种方式获得这些模型之间的关系
1) 自动服务模型
2) 主模型
3) 服务模式
这是我的数据透视表结构
id, auto_service_id, master_id, service_id
现在我需要为每个 AutoService 获取它的 Masters 和他们提供的服务。
一个 Master 可以属于多个 AutoService,并在每个 AutoService 中提供不同的服务。
同一个 AutoService 中的多个 master 可以提供相同的服务。
如何建立这些模型之间的关系?
解决方案
你应该有一个数据透视表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')
.
推荐阅读
- keras - Jupyter notebook - “没有名为 keras 的模块”,但已导入
- php - 在 HTML 中使用 PHP 字符串作为元素 ID
- laravel - Vue 组件可以加载 message.user 但不能加载 message.user.name
- java - 如何从对象列表中将项目添加到 JComboBox
- python - Setuptools python - 项目内的导入问题
- parameters - 在函数中使用与特殊参数同名的局部参数
- javascript - 倒计时嵌入简单的html
- r - 是否有一个 R 函数可以像问题(即帮助)函数一样轻松显示文本
- docker - 在 docker 容器上运行 powershell 或 cmd
- haskell - 如何用 CallStack 抛出异常?