从数据透视表获得一个ID雄辩belongsToMany() - Laravel 5.2
问题描述:
我有两个项目。商店&类别。在我的店里模型我都宣称这种关系:从数据透视表获得一个ID雄辩belongsToMany() - Laravel 5.2
public function categories()
{
return $this->belongsToMany('App\Models\Category');
}
,在我的分类模型我有这样的:
public function shops()
{
return $this->belongsToMany('App\Models\Shop');
}
我能够通过使用附加添加店品类。例如,这代码:
$shop->categories()->attach($cat_id);
通过使用上述附接方法中,记录是在与CATEGORY_ID和shop_id我的透视表category_shop自动创建。
现在,我有一个店加载到$商店。如下所示:
$shop = Shop::findOrFail($id);
很明显,现在我的商店ID在$ shop-> id中。我的问题是如何通过使用上述设置找回这家商店的类别ID。我是laravel新手。
答
因为,商店有很多类别。你会得到很多类别的ID。
$shop= Shop::findOrFail($id);
foreach($shop->categories as $category)
{
print_r($category->id);
}