使用查询生成器创建子查询

时间:2016-09-09 09:04:02

标签: php sql symfony doctrine-orm subquery

我尝试在Doctrine查询构建器中转换SQL查询(工作正常)但我没有成功,因为它包含一个子查询

这是我的SQL查询:

SELECT * 
FROM `navigation` 
WHERE `parent_id` = 
(
     SELECT `id` 
     FROM `navigation` 
     WHERE `parent_id` = 47 
     AND `nav_type`= 'nav'
     AND `published` = 1 
     AND `title` = 'Top'
)

这就是我在存储库中尝试的内容:

class NavigationRepository extends EntityRepository
{
    public function test($parentId, $type, $status, $title)
    {
        $subQuery = $this->createQueryBuilder('n2')
            ->select('n2.id')
            ->where('n2.parent = :parent')
            ->andWhere('n2.type = :type')
            ->andWhere('n2.status = :status')
            ->andWhere('n2.title = :title')
            ->setParameter('parent', $parentId)
            ->setParameter('type', $type)
            ->setParameter('status', $status)
            ->setParameter('title', $title)
            ->getDQL();

        $qb = $this->createQueryBuilder('n');
        $qb
            ->where(
                $qb->expr()->eq('n.parent', '('.$subQuery.')')
            )
            ->getQuery()
            ->getResult();

        return $qb
            ->getQuery()
            ->getResult();
    }
}

但我收到了这个错误:

  

QueryException:参数号无效:绑定变量数   与令牌数量不匹配

为什么?看来我有正确数量的参数......

1 个答案:

答案 0 :(得分:2)

您应该在setParameter()而不是$qb上致电$subQuery。 DQL不包含插值参数,它只是一个常规字符串。