Question

In my repository class i use:

public function getItemsByTag($tag)
{
    $qb = $this->createQueryBuilder('c')
               ->select('c')
               ->where('c.tags LIKE %bipolar%')
               ->addOrderBy('c.id');

    return $qb->getQuery()
              ->getResult();
}

But unfortunately this doesn't work.. Anybody knows how this can work? Or do I have to build a custom query without the QueryBuilder?

Thanks!

Was it helpful?

Solution

If you don't want to substitute your query with variables but use a static string you have to put the string in apostrophes.

You have to use apostrophes instead of quotes! Otherwise the Doctrine2 Lexer will throw an Exception.

So in your case Mike you can use:

'c.tags LIKE \'%bipolar%\''

or

"c.tags like '%bipolar%'"

OTHER TIPS

Searching based on a single parameter:

I think it should go:

public function getItemsByTag($tag)
{
    $qb = $this->createQueryBuilder('c')
           ->select('c')
           ->where('c.tags LIKE :tag')
           ->addOrderBy('c.id')
           ->setParameter('tag', $tag);

    return $qb->getQuery()->getResult();
}

But I think that it is discouraged to do a LIKE as part of a where using the query builder so you should do:

$qb = $this->createQueryBuilder('c');

$qb->select('c')
   ->where($qb->expr()->like('c.tags', '?1'))
   ->addOrderBy('c.id')
   ->setParameter(1, $tag);

return $qb->getQuery()->getResult();

Check out the docs for more information, there is an example of a like expression in the section entitled Helper Methods

I should also point out that I used a different convention in each example for passing a parameter into a query, the first used a named parameter :tag which is set by setParameter('tag', $value) the second is just a numbered parameter ?1, you could have just as easily have used a named parameter in the second example if you wished to as well.

Searching with an array of parameters:

You also asked about doing an array of likes. Here it is with an OR expression but if you wanted to search for all tags you could change it to an AND.

In order to make a "LIKE array" you just have to build up the expression on its own.

$qb = $this->createQueryBuilder('c');

$orExpr = $qb->expr()->orX();

for ($i = 0; $i < count($tags); $i++) {
    $orExpr->add($qb->expr->like('c.tags', "?$i"));

    // You may have to set params later in a loop after $orExpr has been
    // added to the queryBuilder.
    $qb->setParameter($i, $tags[$i]);
}

$qb->select('c')->where($orExpr)->addOrderBy('c.id');

return $qb->getQuery()->getResult();

I don't know much about Symfony, but based on what I know about PHP and MySQL, I imagine you mean 'c.tags LIKE "%bipolar%"'. You likely need quotation marks around %bipolar%.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top