doctrine2 queryBuilder must return only result matching with array values (ids): 0/Null and/or One and/or Many id(s) have to return One result

前端 未结 1 1731
春和景丽
春和景丽 2021-01-24 09:34

I have an array of collection named $configurations. This array matches of my Entity Configuration.php connected to Product.php as a

1条回答
  •  不思量自难忘°
    2021-01-24 10:08

    I had the same problem with Doctrine2 recently and I came with that answer.

    If you want all Product entities that are linked with all the configurations, you need to add a where condition for every configuration.

    Considering your $configurations variable is an array of Configuration entities

    $queryBuilder->select('p')
                 ->from('MyBundle', 'p')
                 ->join('p.workType', 'wt', 'WITH', 'wt.id = p.workType')
                 ->leftJoin('p.configurations','c');
    
    $queryBuilder->where('wt.slug = :slug')->setParameter('slug', $slug);
    
    $nbConfs = count($configurations);
      for($i = 0; $i < count($configurations); $i++){
          $queryBuilder->andWhere(":conf{$i} MEMBER OF p.configurations")->setParameter("conf{$i}", $configurations[$i]);
      }
    
    $queryBuilder
          ->having('COUNT(c.id) =:some_count')
          ->setParameter('some_count', $nbConfs);
    

    I had to use a for loop to create different tokens (the string preceded by :), otherwise Doctrine doesn't add them to its internal collection of parameters.

    Edit : Query modified to consider the case where you pass no configurations and want to get Products that has no relations to Configurations.

    0 讨论(0)
提交回复
热议问题