簡體   English   中英

我有 3 個有關系的表。 第一個表具有另一個兩個表的外部 id。 我想知道獲取數據的確切查詢

[英]I have 3 tables with relation. The first table have foreign id of another both tables. I want to know the exact query of fetching the data

  1. 3款-

1.1) 產品 MODEL -

class Product extends Model
{

    protected $table = 'product_table(TableName)';

    public function banks()
    {
        return $this->belongsToMany(Bank::class, 'bank_table', 'bank_id(ForeignKey)', 'id(PrimaryKey)');
    }

    public function product_category()
    {
       return $this->belongsToMany(ProductCategory::class, 'productcategory_table', 'productcategory_id(ForeignKey)', 'id(PrimaryKey)');
    }

}

1.2) 銀行 MODEL -

class Bank extends Model
{
    protected $table = 'bank_table(TableName)';

    public function product()
    {
        return $this->hasMany('App\Models\Product', 'id(PrimaryKey)', 'bank_id(ForeignKey)');
    }
}

1.3) 產品類別 MODEL -

class ProductCatgory extends Model
{
    protected $table = 'mudra5_productcategory';
    
     public function mudra5_product()
    {
        return $this->hasMany('App\Models\Product');
    }
}
  1. CONTROLLER 代碼 -
public function cat()
{
    $alldata = Bank::with(['product'])->first();
    dd($alldata->product[0]->product_name);
}

3.路線 -

Route::get('/borrower_profile', 'BorrowerAuth\statementController@cat')->name('mudra5_product');

  1. 表 -

4.1) 產品表 -

id(int PK) 產品名稱(varchar(100)) bank_id(外鍵) category_id(外鍵)
1 p1
2 p2

4.2) 銀行表-

id(int PK) 銀行名稱 銀行標志
1 銀行1 圖像1
2 銀行2 img2

4.3) 產品類別表 -

id(int PK) 分類名稱
1 貓1
2 貓2

OUTPUT 應該是 -

ID 分類名稱 銀行名稱 產品名稱
1 貓1 銀行 1 銀行 2 銀行 3 p1/p2/p3(bank1), p1/p2(bank2), p1/p2/p3(bank3)
2 貓2 銀行 1 銀行 2 銀行 3 p1/p2/p3(bank1), p1/p2/p3(bank2), p1/p2/p3(bank3)

如果放置外鍵,則關系為 HasMany-belongsTo (1-N),例如,如果每個產品都有一個類別,那么我們將 category_id 的外鍵放在產品表中,因為它只能是一個。

在您的情況下,您使用了belongsToMany而不是belongsTo,因此一個產品可以有很多類別,但您還在表中放置了一個外鍵,它與belongsToMany一起dosnt go。

你不能把 hasMany 和 belongsToMany 放在一起。 選擇其中之一。

一個belongsToMany 是一個用於NN 關系的eloquent 關系,它們需要一個pivot 表,沒有表可以保存另一個_id,因此您創建一個具有兩個id 的picot 表,該表將處理關系查詢流量。

如果你想保護你呈現的關系而不是你需要 5 個表(不是 3 個)

產品分類 銀行類_產品銀行_產品

產品

ID 產品名稱
1 p1
2 p2

類別

ID 分類名稱
1 c1
2 c2

銀行

ID 銀行名稱
1 b1
2 b2

類別_產品

ID catrgory_id product_id
1 1 2
2 2 1

銀行產品

ID 銀行ID product_id
1 1 2
2 2 1

楷模

我你 go 通過文檔你不必指定外鍵名的表名 laravel 如果你做了命名權就會自己發現它,

Controller

第一個產品:

    public function cat()
    {
        $firstBank= Bank::first();
        dd($firstBank->products()->first()->product_name);
    }

與您的示例相同的 output 嗎? :每個類別及其銀行及其產品

    public function cat()
    {
        dd(Catgeory::with('banks' , 'products')->get());
    }

請查看 eloquent ORM 的官方文檔這里它通過示例解釋了很多事情

檢查此 repo以獲取標簽和帖子之間的多對多關系的參考

暫無
暫無

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

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