gpt4 book ai didi

php - Doctrine 查询生成器 : ManyToOne Relationship where more than one subEntity must match

转载 作者:行者123 更新时间:2023-11-30 21:21:49 25 4
gpt4 key购买 nike

我正在尝试进行查询,其中我有一个实体 Job 和一个实体 JobProperty,其中 1 个 Job 可以有多个 作业属性

Query on a many-to-many relationship using Doctrine with Symfony2解释了如何根据一个实体的子实体的值检索一个实体的匹配项。由此我构建了查询:

$qb = $this->getDoctrine()->getRepository('AppBundle:Job')->createQueryBuilder('job')
->innerJoin('job.properties','property');

foreach($filters as $label => $value)
{
$qb->andWhere('property.label = :label AND property.value = :value')
->setParameter('label',$label)
->setParameter('value',$value);
}

上面的查询在一定程度上有效,但它提供了属性与任何过滤器匹配的结果,而不仅仅是提供匹配所有过滤器的结果。我需要它只返回匹配所有过滤器的结果。

我可能不得不以不同的方式解决这个问题,但我不确定我是否会实现。

最佳答案

你做的不正确你正在将标签和值与最后一个过滤器值匹配,因为查询中使用的占位符 :label:value 对每个人来说都不是唯一的循环迭代,因此循环生成的所有子句都将匹配最后的标签和值。

要获得其每个属性都与提供的过滤器相匹配的职位,您可以编写类似于以下 Doctrine 的查询。

首先它会将所有标签和值收集到单独的数组中,然后使用 IN() 操作与作业的属性进行匹配,最后获取其属性与您的所有过滤器匹配的作业需要建立聚合来统计匹配结果,并且应该等于过滤器的数量

$qb =  $this->getDoctrine()
->getRepository('AppBundle:Job')
->createQueryBuilder('job')
->innerJoin('job.properties','p');
$labels = array();
$values = array();
foreach($filters as $label => $value)
{
$labels[] = $label;
$values[] = $value;
}
$qb->addSelect('COUNT(DISTINCT p.id) AS total_properties')
->andWhere('p.label IN (:labels)')
->andWhere('p.value IN (:values)')
->addGroupBy('job.id')
->having('total_properties = '.count($filters))
->setParameter('labels',$labels)
->setParameter('values',$values)
->getQuery()
->getResult();

Here is another answer as a reference here which is similar to your question Symfony2 - Doctrine2 QueryBuilder WHERE IN ManyToMany field

关于php - Doctrine 查询生成器 : ManyToOne Relationship where more than one subEntity must match,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46930493/

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