Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine setParameter and Invalid parameter number

After many tries, I think I finally know the documentation by heart. Then, I need your help .. I don't understand why Doctrine show me this error :

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

Here is my code :

$qb = $this->em->createQueryBuilder();
$qb->select('m')
   ->from('Entities\Marque', 'm')
   ->leftJoin('m.magasin', 'ma')
   ->where('m.nom = :marque AND ma.nom LIKE :magasin')
   ->setParameter('marque', $marque)
   ->setParameter('magasin', '%'.$matchesNumber[1].'%');
$results = $qb->getQuery()->getArrayResult();

Thank you in advance for your answer.

like image 671
Florian Mithieux Avatar asked Apr 15 '13 14:04

Florian Mithieux


2 Answers

This also happens if you accidentally use more than one where(), which happened to me once.

$em    = $this->getEntityManager();
$query = $em->createQueryBuilder()
    ->from('AppBundle:SomeEntity', 's')
    ->select('s')
    ->where('s.foo = :foo')
    ->where('s.bar = :bar') // <- HERE
    ->setParameter('foo', 'Foo Value')
    ->setParameter('bar', 'Bar Value');

Should be:

$em    = $this->getEntityManager();
$query = $em->createQueryBuilder()
    ->from('AppBundle:SomeEntity', 's')
    ->select('s')
    ->where('s.foo = :foo')
    ->andWhere('s.bar = :bar') // <- CHANGE TO andWhere()
    ->setParameter('foo', 'Foo Value')
    ->setParameter('bar', 'Bar Value');

Hope this helps someone.

like image 127
Yes Barry Avatar answered Oct 02 '22 06:10

Yes Barry


I presume ->setParameter overrides the previous one.

For multiple Parameters use:

->setParameters(['key1' => $value1, 'key2' => $value2])

See Doctrine Upgrade:

From now on, parameters in queries is an ArrayCollection instead of a simple array. This >affects heavily the usage of setParameters(), because it will not append anymore parameters >to query, but will actually override the already defined ones. Whenever you are retrieving a >parameter (ie. $query->getParameter(1))

Doctrine Upgrade Description

Maybe that also applies to setParameter?

like image 29
DerStoffel Avatar answered Oct 02 '22 05:10

DerStoffel