3

I try to convert SQL query (which works fine) in Doctrine query builder but I do not succeed because it contains a sub query

This is my SQL Query :

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

And this is what I tried in my Repository :

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

But I got this error :

QueryException: Invalid parameter number: number of bound variables does not match number of tokens

Why ? It seems I have the right number of parameter yet...

1 Answer 1

2

You should call setParameter() on $qb instead of $subQuery. The DQL doesn't contain interpolated parameters, it's just a regular string.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't know what your query does or what your database looks like. You asked about the incorrect number of parameters.
yes indeed thanks, I update my answer with your solution and I put how I call my query
Try dumping the SQL query with ->getQuery()->getSql() and manually check what it generated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.