簡體   English   中英

Laravel:3個表之間的模型關系

[英]Laravel : Model Relations between 3 tables

我有 3 個表shopsbusiness_categoriesshop_categories如下

  1. 業務類別持有擁有所有類別
  2. 店鋪有店鋪數據
  3. 商店類別具有分配給商店的商店和業務類別的 ID

我需要列出帶有商店列表的類別名稱。 我能夠獲得類別,但不確定如何關聯第三張表

在我的Shop Model

 public function shopCategories(){
    return $this->belongsTo(ShopCategory::class,'shop_id','shop_id');
 }

在我的控制器中

Shop::with('shopCategories')->get()

這會從shop_categories表中返回商店和數據,但我不確定如何將shop_categoriesbusiness_categories表相關聯

編輯 ::

業務類別

在此處輸入圖像描述

shop_categories

在此處輸入圖像描述

店鋪

在此處輸入圖像描述

基本上你在ShopBusinessCategory模型之間有經典的多對多關系(每個商店可以有很多類別,類別可以有很多商店),所以

  1. 在表shop_categories你不需要字段shop_category_id因為中間表大多不使用主鍵
  2. 定義標准多對多關系
//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. 現在,當在控制器中設置關系時,您可以這樣做
$categoriesWithShops = BusinessCategory::with('shops')->get();

並通過商店列表獲得所需的類別

這種方式不會讓您放棄ShopCategory模型並停止使用它(如果需要),而是探索一些美麗的東西,如synctoggle等定義的關系

使用 laravel Has Many Through關系模型:

在您的商店類別模型中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM