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

标签 php mysql symfony doctrine-orm doctrine

我正在尝试进行查询,其中我有一个实体 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/

相关文章:

php - 提高网站性能

mysql - 表达式引擎 : git : local development : remote database

php - 从数据库检索数据出现错误

php - 使 SQLITE 触发器与 MYSQL 一起工作

php - 在yii2中通过ajax验证表单

php - date_add 或 date_sub 速度差异?

security - Symfony2 每主机访问控制

html - 将 novalidate 属性包含到 Symfony2 twig 模板中

php - 如何在 sonata admin Admin Controller 中设置 flash 消息

PHP:NULLish 值检查