i have 3 tables shops
, business_categories
, shop_categories
as below
- Business Categories holds has all the categories
- Shop has shops data
- Shop categories has ids for shops and businiess categories which are assigned to shop
I need to list the category names with shop listing. i am able to get categories but not sure how can i relate 3rd table
in my Shop Model
public function shopCategories(){
return $this->belongsTo(ShopCategory::class,'shop_id','shop_id');
}
In my controller
Shop::with('shopCategories')->get()
this returns me shops and data from shop_categories
table but i am not sure how can i relate shop_categories
to business_categories
table
Edit ::
business_categories
shop_categories
shop
CodePudding user response:
Define this relationship In ShopCategory Model :
public function businessCategories(){
return $this->belongsTo(BusinessCategory::class,'business_category_id','id');
}
In your controller method :
Shop::with('shopCategories.businessCategories')->get();
CodePudding user response:
Use laravel Has Many Through relation model:
In your shop categories model:
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...
);
}