Home > Mobile >  Laravel : Model Relations between 3 tables
Laravel : Model Relations between 3 tables

Time:05-20

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

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...
    );
}
  • Related