[英]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);
工廠表:
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.