Search code examples
symfonydoctrine-ormdqlquery-string

how to search array words with Doctrine DQL using bucle


i'm trying to search words stored in array in this way:

$dql_cat =' SELECT c
                FROM FrontendBundle:Categoria c
                WHERE';

        foreach ($palabras as $palabra){    

            if ($palabra === reset($palabras)){
                $dql_cat .= ' c.nombre LIKE %'.$palabra.'%';
            }
            else{
                $dql_cat .= ' OR c.nombre LIKE %'.$palabra.'%';
            }               
        }

        $dql_cat .= ' ORDER BY c.nombre';       
        $query = $em->createQuery($dql_cat);            
        $resultados['categorias'] = $query->getResult();

But i get an exception with the query.

Query result:

SELECT c FROM FrontendBundle:Categoria c WHERE c.nombre LIKE %carpinteria% OR c.nombre LIKE %aluminio% ORDER BY c.nombre

Query exception:

QueryException: [Syntax Error] line 0, col 98: Error: Expected StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression, got '%'

I think that is more proper to use queryBuilder to avoid mistakes but i don't know how to use it with a parameters array.

I need a solution with or without queryBuilder.

Thanks.


Solution

  • queryBuilder would be as follows:

    $qb = $em->createQueryBuilder();
            $qb->select('c')
                ->from('FrontendBundle:Categoria', 'c');
    
            foreach ($palabras as $palabra){
                if ($palabra === reset($palabras)){
                    $qb->where($qb->expr()->like('c.nombre', $qb->expr()->literal('%' . $palabra . '%')));
                }                                       
                $qb->orWhere($qb->expr()->like('c.nombre', $qb->expr()->literal('%' . $palabra . '%')));
            }
    
            $query = $qb->orderBy('c.nombre', 'ASC')
            ->getQuery();
    
            $resultados['categorias'] = $query->getResult();