2016-09-16 118 views
1

我想搜索未分配给房间的人。我做了以下查询:学说:主要实体ID在子查询数组中的子查询

public function findByWithoutRoom() 
{ 
    $qb = $this->getEntityManager()->createQueryBuilder(); 
    $qb2 = $this->getEntityManager()->createQueryBuilder(); 

    $qb 
     ->select('p') 
     ->from('MyPeopleBundle:Person', 'p') 

     ->where(
      $qb->expr()->exists(
       $qb2->select('r') 
        ->from('MyAccommodationBundle:Room', 'r') 
        ->andWhere($qb2->expr()->like('r.currentPeople', ':person')) 
        ->setParameter('person', '%i:'.$person_id.';%') 

        ->getDQL() 
      ) 
     ) 

    $result = $qb->getQuery()->execute(); 
    return $result; 
} 

我该如何让p.id代替person_id?注:currentPeople属性的类型为 “数组” 的(而不是 “simple_array”)

UPDATE:

我也试过如下:

public function finByWithoutRoom() 
{ 
    $qb = $this->getEntityManager()->createQueryBuilder(); 
    $qb 
     ->select('p') 
     ->from('MyPeopleBundle:Person', 'p') 
     ->leftJoin('MyAccommodationBundleV2:Room', 'r') 
     ->andWhere($qb->expr()->like('r.currentPeople', '%i:p.id%')); 

    $result = $qb->getQuery()->execute(); 
    return $result; 
} 

然而,这给了我以下错误:

[Syntax Error] line 0, col 114: Error: Expected StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression, got '%' 

回答

1

您可以使用主查询的直接的别名,如例如:

$qb 
    ->select('p') 
    ->from('MyPeopleBundle:Person', 'p') 
    ->where(
     $qb->expr()->isNotNull(
      $qb2->select('r') 
       ->from('MyAccommodationBundle:Room', 'r') 
       ->andWhere($qb->expr()->like('r.currentPeople', 'p.id')) 

       ->getDQL() 
     ) 
    ) 

    ->setParameter('from', $from) 
    ->setParameter('to', $to); 

我建议使用not exists而不是is not null(但我认为是相同的结果)。如例:

$qb->andWhere($qb->expr()->not($qb->expr()->exists($qb2->getDQL()))); 

希望这有助于

+1

的感谢!我目前正在检查这个。我想知道是否有一个人的ID为100和一个人的ID为1000,它可能会返回“不为空”,而这可能不是这样。 p.id也可能发生在数组的其他地方。将很快回到这一点。 – apfz

+0

它只适用于我 - > setParameter(':myid','%i:556%'),其中556是硬编码的p.id。有没有一种方法可以让我在你指定的格式中添加通配符? ($ qb-> expr() - > like('r.currentPeople','p.id')) – apfz

+0

我们可以按照[这里]所述使用SQL concat(http://stackoverflow.com/a/4420559/2270041 ),但取决于你使用的教条版本,如果有这个[pr](https://github.com/doctrine/doctrine2/pull/1397)。 – Matteo