簡體   English   中英

如何在MySQL中的多對多關系中獲取與另一個表中的所有記錄有關系的記錄?

[英]How to get records that has relationship with all records in another table in many to many relationships in MySQL?

我正在使用 Laravel 8 和 MySQL8。 我有這些表:

products
    id - integer
    name - string

factories
    id - integer
    name - string

factory_product
    factory_id - integer
    product_id - integer

如您所見, products表與factories表具有多對多的關系。 現在我想得到所有工廠生產的產品。

換句話說,我想從與所有factories記錄有關系的products中選擇記錄。 怎么做? 我需要SQL代碼。

試試這個查詢:

SELECT product_id
FROM factory_product
GROUP BY product_id
HAVING COUNT(factory_id) = (SELECT COUNT(*) FROM factories);

dbfiddle 演示鏈接

工廠表:

ID 姓名
f1 F A
f2 臉書
f3 fc
f4 fd
f5

產品表:

ID 姓名
p1
p2
p3 個人電腦

工廠_產品表:

factory_id product_id
f1 p1
f1 p2
f1 p3
f2 p1
f2 p3
f3 p1
f3 p3
f4 p1
f4 p3
f4 p2
f5 p1
f5 p2
f5 p3

我的查詢產生的輸出:

product_id
p1
p3

通過使用 belongsToMany 關系

  • 在這里這個功能添加到您的產品模型中

    public function withFactories() { return $this->belongsToMany(factories::class, factory_product::class,'product_id', 'factory_id'); }

  • 在控制器中添加功能

    $all_product = products::with('withFactories)->get();

  • 這里必須在 factory_product 表中有外鍵

  • 在這里,您可以在 withFactories 數組中獲取產品價值和工廠詳細信息的價值

暫無
暫無

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

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