如何在MySQL中的多对多关系中获取与另一个table中的所有记录有关系的记录?
How to get records that has relationship with all records in another table in many to many relationships in MySQL?
我正在使用 Laravel 8 和 MySQL8。
我有这些 tables:
products
id - integer
name - string
factories
id - integer
name - string
factory_product
factory_id - integer
product_id - integer
如您所见,products
table 与 factories
table 具有多对多关系。
现在我想得到所有工厂生产的产品。
怎么做?
我需要 SQL
代码。
通过使用 belongsToMany 关系
此处将此功能添加到您的产品模型中
public function withFactories() { return $this->belongsToMany(factories::class, factory_product::class,'product_id', 'factory_id'); }
在控制器中添加功能
$all_product = products::with('withFactories)->get();
这里必须有外键在factory_product table
在这里您可以在 withFactories 数组中获取产品价值和工厂详细信息的价值
试试这个查询:
SELECT product_id
FROM factory_product
GROUP BY product_id
HAVING COUNT(factory_id) = (SELECT COUNT(*) FROM factories);
工厂 Table:
id
name
f1
fa
f2
fb
f3
fc
f4
fd
f5
fe
产品 Table:
id
name
p1
pa
p2
pb
p3
pc
Factory_Product Table:
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
我正在使用 Laravel 8 和 MySQL8。 我有这些 tables:
products
id - integer
name - string
factories
id - integer
name - string
factory_product
factory_id - integer
product_id - integer
如您所见,products
table 与 factories
table 具有多对多关系。
现在我想得到所有工厂生产的产品。
怎么做?
我需要 SQL
代码。
通过使用 belongsToMany 关系
此处将此功能添加到您的产品模型中
public function withFactories() { return $this->belongsToMany(factories::class, factory_product::class,'product_id', 'factory_id'); }
在控制器中添加功能
$all_product = products::with('withFactories)->get();
这里必须有外键在factory_product table
在这里您可以在 withFactories 数组中获取产品价值和工厂详细信息的价值
试试这个查询:
SELECT product_id
FROM factory_product
GROUP BY product_id
HAVING COUNT(factory_id) = (SELECT COUNT(*) FROM factories);
工厂 Table:
id | name |
---|---|
f1 | fa |
f2 | fb |
f3 | fc |
f4 | fd |
f5 | fe |
产品 Table:
id | name |
---|---|
p1 | pa |
p2 | pb |
p3 | pc |
Factory_Product Table:
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 |