Doctrine 2 WHERE IN clause using a collection of entities

前端 未结 4 718
太阳男子
太阳男子 2020-12-09 09:27

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.<

相关标签:
4条回答
  • 2020-12-09 09:38

    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);
    ;
    
    0 讨论(0)
  • 2020-12-09 09:52

    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();
    
    0 讨论(0)
  • 2020-12-09 09:54

    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.

    0 讨论(0)
  • 2020-12-09 09:58

    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.

    0 讨论(0)
提交回复
热议问题