Search code examples
phpsymfonydoctrine-ormsymfony-2.1dql

Query with an array of likes in Doctrine & Symfony 2.1


I have an array of terms that I would like to match using the LIKE wildcard in one Doctrine 2 query. The database is SQL and I'm using DQL but a query builder solution would be fine. My current query setup is this:

foreach($textterms as $text)
{
$parameters[] = '%-'.$text.'-%';
}

$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT p FROM Post p WHERE p.searchfield IN LIKE (:text) ORDER BY p.datetime DESC'
        )->setParameter('text', $parameters);
        $posts = $query->getResult();

But I get the symfony error "QueryException: [Syntax Error] line 0, col 62: Error: Expected Literal, got '('"

Is this query possible in doctrine?


Solution

  • You're receiving such error because query is expecting a value after LIKE statement. There is no such a thing like "IN LIKE". Possible solutions which I would consider:

    // Query Builder added to show difference in code readability I personally use queryBuilder mostly
    $query = $this->getDoctrine()->getManager()->createQueryBuilder();
    $query->select('p')
            ->from('Post', 'p')
            ->orderBy('p.datetime', 'DESC');
    $i = 0;
    $parameters = array();
    foreach ($textterms as $key => $text)
    {
        $query->orWhere('p.searchfield LIKE ?' . $i++);
        $parameters[] = '%-' . $text . '-%';
    }
    $query->setParameters($parameters);
    $posts = $query->getQuery()->getResult();
    
    // Query
    $orX = new \Doctrine\ORM\Query\Expr\Orx();
    $i = 0;
    $parameters = array();
    foreach ($textterms as $text)
    {
        $orX->add('p.searchfield LIKE ?' . $i++);
        $parameters[] = '%-' . $text . '-%';
    }
    $orX = (string)$orX;
    if(!empty($orX))
    {
        $orX = 'WHERE ' . $orX;
    }
    $sql = sprintf('SELECT p FROM Post p %s ORDER BY p.datetime DESC', $orX);
    $query = $this->getDoctrine()->getManager()->createQuery($sql);
    $query->setParameters($parameters);
    $posts = $query->getResult();