stackoverflow account
stackoverflow account

Reputation: 235

Laravel : Model Relations between 3 tables

i have 3 tables shops , business_categories , shop_categories as below

  1. Business Categories holds has all the categories
  2. Shop has shops data
  3. 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

enter image description here

shop_categories

enter image description here

shop

enter image description here

Upvotes: 0

Views: 833

Answers (2)

Ol D. Castor
Ol D. Castor

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

  1. in table shop_categories you don't need field shop_category_id as intermidiate tables mostly don't use primary keys
  2. defining standard many-to-many relation
//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');
}
  1. now when relation is set in controller you may do
$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

Faizan Ali
Faizan Ali

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

Related Questions