gpt4 book ai didi

symfony - Doctrine 多对多查询

转载 作者:行者123 更新时间:2023-12-01 11:39:29 25 4
gpt4 key购买 nike

我有一个产品实体,它与分类单元实体具有多对多关系。我想找到属于所有分类单元交集的所有产品。例如,我想找到属于 ID 为 1 和 2 的类群的所有产品。

Products
{1,2,3}

Taxons
{1,2,3,4,5}

ProductsToTaxons
{{p1,t1},{p1,t2}, {p2,t2}}

我只想在查询分类单元 1 和 2 的产品时检索以下集合:

Product
{1}
which is from {{p1,t1}, {p1,t2}}

好的,这是我尝试过的 DQL...但它不起作用?

SELECT p FROM SRCProductBundle:Product p
JOIN p.taxons t
WHERE t.id = 1 AND t.id = 2

(P.S. 我也会用 QueryBuilder 来做这件事)

编辑

澄清一下,这是我想转换成 DQL/QueryBuilder 的 SQL。

select p.id 
from product p
where exists (select product_id
from product_to_taxon
where taxon_id = 1
and product_id = p.id)
and exists (select product_id
from product_to_taxon
where taxon_id = 4
and product_id = p.id);

最佳答案

您可以使用 MEMBER OF 语句来实现这一点,尽管根据我的经验,它在多对多关系中并没有产生非常高效的结果:在 DQL 中:

SELECT p FROM SRCProductBundle:Product p
WHERE 1 MEMBER OF p.taxons OR 2 MEMBER OF p.taxons

或者使用查询生成器

$this->createQueryBuilder('p')
->where(':taxon_ids MEMBER OF p.taxons')
->setParameter('taxon_ids', $taxonIdsArray)
->getQuery()
->getResult();

这将创建类似于提供的示例的 SQL,尽管根据我的经验,它仍然在 EXISTS 子查询中有一个连接。也许 Doctrine 的 future 版本可以解决这个问题。

关于symfony - Doctrine 多对多查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22872876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com