Doctrine:子查询,其中主实体id在子查询数组中

时间:2016-09-16 07:44:30

标签: doctrine-orm

我想搜索未分配到房间的人。我做了以下查询:

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属性的类型为“array”(不是“simple_array”)

更新:

我也尝试了以下内容:

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 个答案:

答案 0 :(得分:2)

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

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

希望这个帮助