How to set parameters in nested query in DQL

2019-06-07 01:22发布

问题:

Hi, I'd like to get number of created articles by a user, the query used to work until I added some parameters filtering the query by "fromDate" and "toDate" dates, here's my query :

// query String
$dql = 'SELECT u.idUser,
               u.lastName,
               u.email,
               u.mobile,
               (SELECT AVG(n.note)
                FROM MyBundle:Note n
                WHERE n.noteFor = u.idUser) AS note,
               (SELECT COUNT(a) 
                FROM MyBundle:Article a 
                WHERE (a.createdBy = u.idUser) AND (a.createdAt BETWEEN :fromDate AND :toDate)) AS articles
         FROM MyBundle:User u';

// create the actual query
$users= $em->createQuery($dql);
// set filter date parameter
$users->setParameter('fromDate', $fromDate.'00:00:00');
$users->setParameter('toDate', $toDate.'23:59:59');

I keep getting this error : Invalid parameter number: number of bound variables does not match number of tokens. I tried searching in the doctrine documentation for how to set parameters in nested queries without finding anything. first I need to know if it's possible to do that then find where the error come from, Please Help !

回答1:

Use setParameters() instead of setParameter()

$users->setParameters(array('fromDate'=> $fromDate.'00:00:00','toDate'=> $toDate.'23:59:59'))


回答2:

So after performing some tests, I found out that the query worked well the way it was and the problem wasn't there. I'm using KnpPaginatorBundle to paginate my queries, it seems that the problem was that it couldn't paginate complex queries like passing multiple parameters in the nested query. so I found a solution.
So this is the old code :

// Pagination
$paginator = $this->get('knp_paginator');
$users     = $paginator->paginate($users, 1, 10);

And this is the new code :

// Pagination
$paginator = $this->get('knp_paginator');
$users     = $paginator->paginate($users, 1, 10, array('wrap-queries' => true) );

Thanks to Nisam and Matteo for their time, hope this helps someone