Reputation: 235
i have 3 tables shops
, business_categories
, shop_categories
as below
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
Upvotes: 0
Views: 833
Reputation: 563
basically you have classic Many-To-Many relation between Shop
and BusinessCategory
models (each shop can have many categories and category can have many shops), so
shop_category_id
as intermidiate tables mostly don't use primary keys//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();
and get desired categories with shops listing
this way don't makes you to drop ShopCategory
model and stop using it (if needed), but explores some beautiful things like sync
, toggle
etc for defined relation
Upvotes: 2
Reputation: 330
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...
);
}
Upvotes: 0