Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2 WHERE IN clause using a collection of entities

Tags:

I'm attempting to build a query in Doctrine 2 that finds all Vacancy entities which are related to any of the given VacancyWorkingHours entities.

The Vacancy entity looks as follows:

/**  * Vacancy  *  * @ORM\Table(name="vacancy")  * @ORM\Entity(repositoryClass="JaikDean\CareersBundle\Entity\VacancyRepository")  */ class Vacancy {     /**      * @var integer      *      * @ORM\Column(name="id", type="integer")      * @ORM\Id      * @ORM\GeneratedValue(strategy="AUTO")      */     private $id;      /**      * @var VacancyWorkingHours      *      * @ORM\ManyToOne(targetEntity="VacancyWorkingHours", inversedBy="vacancies")      * @ORM\JoinColumn(name="vacancy_working_hours_id", referencedColumnName="id")      **/     private $workingHours;      /* Other fields and methods are inconsequential */ } 

My query currently looks as follows, but returns no results because of the where clause. In this example, $workingHours is a Doctrine\Common\Collections\ArrayCollection instance containing a number of VacancyWorkingHours entities

$q = $this->createQueryBuilder('v')     ->select('v')     ->andWhere('v.workingHours IN (:workingHours)')     ->setParameter('workingHours', $workingHours->toArray()); ; 
like image 458
Jaik Dean Avatar asked Aug 30 '13 15:08

Jaik Dean


1 Answers

A pull request I made about this has been merged into Doctrine ORM 2.5, so you can simply do this now:

$q = $this->createQueryBuilder('v')     ->select('v')     ->andWhere('v.workingHours IN (:workingHours)')     ->setParameter('workingHours', $workingHours); ; 

The latest version of Doctrine now allows collection parameters and will automatically make use of the primary key of each of the collection entries.

like image 158
Michaël Perrin Avatar answered Oct 02 '22 18:10

Michaël Perrin