简体   繁体   中英

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

在此处输入图像描述

shop_categories

在此处输入图像描述

shop

在此处输入图像描述

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM