[英]Laravel : Model Relations between 3 tables
我有 3 個表shops
, business_categories
, shop_categories
如下
我需要列出帶有商店列表的類別名稱。 我能夠獲得類別,但不確定如何關聯第三張表
在我的Shop Model
中
public function shopCategories(){
return $this->belongsTo(ShopCategory::class,'shop_id','shop_id');
}
在我的控制器中
Shop::with('shopCategories')->get()
這會從shop_categories
表中返回商店和數據,但我不確定如何將shop_categories
與business_categories
表相關聯
編輯 ::
業務類別
shop_categories
店鋪
基本上你在Shop
和BusinessCategory
模型之間有經典的多對多關系(每個商店可以有很多類別,類別可以有很多商店),所以
shop_category_id
因為中間表大多不使用主鍵//Shop model
public function categories() {
return $this->belongsToMany(BusinessCategory::class, 'shop_categories', 'business_category_id', 'shop_id');
}
//BusinessCategory model
public function shops() {
return $this->belongsToMany(Shop::class, 'shop_categories', 'shop_id', 'business_category_id');
}
$categoriesWithShops = BusinessCategory::with('shops')->get();
並通過商店列表獲得所需的類別
這種方式不會讓您放棄ShopCategory
模型並停止使用它(如果需要),而是探索一些美麗的東西,如sync
、 toggle
等定義的關系
使用 laravel Has Many Through關系模型:
在您的商店類別模型中:
public function shopCategories()
{
return $this->hasManyThrough(
Shop::class,
business_categories::class,
'shop_id', // Foreign key on the shop table...
'business_category_id', // Foreign key on the business table...
'id', // Local key on the shop table...
'id' // Local key on the business table...
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.