【发布时间】:2019-10-01 16:38:25
【问题描述】:
Laravel 是否可以通过 belongsToMany 关系来建立关系?
我有 4 张桌子:
1)Restaurants (id , name) - 将 hasManyRelation 与 Workers 表一起使用
2)董事(id,姓名)
3)Directors_Restaurants (id, director_id, restaurant_id) - 用于将 belongsToMany 餐厅与董事联系起来的数据透视表
3)Workers (id, name, restaurant_id)
通过 Director 模型中的此功能,我可以获得所有连接的餐厅
public function restaurants()
{
return $this->belongsToMany('App\Restaurant','director_restaurant');
}
通过我的代码中的这个函数,我可以得到一个董事所有餐厅的所有工人
$director = Director::find(1);
$director->load('restaurants.workers');
$workers = $director->restaurants->pluck('workers')->collapse();
所以我的问题是:我可以在我的 Director 模型中声明类似的关系以获取所有餐厅的所有工人吗?
【问题讨论】: