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

2022-01-16 00:00:00 orm php symfony doctrine doctrine-orm

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

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.

Vacancy 实体如下所示:

/**
 * Vacancy
 *
 * @ORMTable(name="vacancy")
 * @ORMEntity(repositoryClass="JaikDeanCareersBundleEntityVacancyRepository")
 */
class Vacancy
{
    /**
     * @var integer
     *
     * @ORMColumn(name="id", type="integer")
     * @ORMId
     * @ORMGeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var VacancyWorkingHours
     *
     * @ORMManyToOne(targetEntity="VacancyWorkingHours", inversedBy="vacancies")
     * @ORMJoinColumn(name="vacancy_working_hours_id", referencedColumnName="id")
     **/
    private $workingHours;

    /* Other fields and methods are inconsequential */
}

我的查询当前如下所示,但由于 where 子句,没有返回任何结果.在此示例中,$workingHours 是一个 DoctrineCommonCollectionsArrayCollection 实例,其中包含许多 VacancyWorkingHours 实体

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

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

推荐答案

一个 拉取请求 我提出了这个问题已合并到 Doctrine ORM 2.5 中,因此您现在可以简单地执行此操作:

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

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

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

相关文章