Doctrine 2 WHERE IN子句使用实体集合

时间:2013-08-30 15:08:45

标签: php symfony orm doctrine-orm doctrine

我尝试在Doctrine 2中构建查询,查找与任何给定Vacancy实体相关的所有VacancyWorkingHours个实体。

Vacancy实体如下所示:

/**
 * 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 */
}

我的查询目前看起来如下,但由于where子句没有返回结果。在此示例中,$workingHours是包含多个Doctrine\Common\Collections\ArrayCollection实体的VacancyWorkingHours实例

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

4 个答案:

答案 0 :(得分:26)

我对此做出的pull request已合并到Doctrine ORM 2.5中,因此您现在可以直接执行此操作:

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

最新版本的Doctrine现在允许收集参数,并会自动使用每个集合条目的主键。

答案 1 :(得分:17)

尝试将ID设置为参数

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

然后

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

答案 2 :(得分:0)

我认为DQL会更好地发挥作用。

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

答案 3 :(得分:0)

我建议以这种方式使用DQL:

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

然后让Doctrine为您处理表达式和报价。