原则 2 WHERE IN 条款使用实体集合

2022-08-30 18:20:26

我试图在教义2中构建一个查询,以查找与任何给定实体相关的所有实体。VacancyVacancyWorkingHours

实体如下所示: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 子句,不返回任何结果。在此示例中,是一个包含多个实体的实例$workingHoursDoctrine\Common\Collections\ArrayCollectionVacancyWorkingHours

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

答案 1

我对此提出的拉取请求已合并到 Doctrine ORM 2.5 中,因此您现在可以简单地执行此操作:

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

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


答案 2

尝试将 ID 设置为参数

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

然后

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

推荐