Doctrine 2 WHERE IN clause using a collection of e

2020-02-04 07:06发布

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());
;

4条回答
手持菜刀,她持情操
2楼-- · 2020-02-04 07:37

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.

查看更多
Viruses.
3楼-- · 2020-02-04 07:53

Try to set IDs as parameter

$ids = array();
foreach($workingHours as $w) {
    $ids[] = $w->getId();
}

Then

$q = $this->createQueryBuilder('v')
    ->select('v')
    ->andWhere('v.workingHours IN (:workingHours)')
    ->setParameter('workingHours', $ids);
;
查看更多
ら.Afraid
4楼-- · 2020-02-04 08:02

I think the DQL will work better for that.

$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery(
    'SELECT v
    FROM YourAppYourBundle:YourEntity v // exemple AcmeexampleBundle:YourEntity
    WHERE v.workingHours IN :workingHours'
)->setParameter('workingHours', $workingHours->toArray());

$vacancies = $query->getResult();
查看更多
三岁会撩人
5楼-- · 2020-02-04 08:02

I suggest using DQL in this way:

$qb = $this->createQueryBuilder('v')
    ->andWhere($qb->expr()->in('v.workingHours', $ids));
;

And let Doctrine handle the expression & quotation work for you.

查看更多
登录 后发表回答