1

I'm trying to update a Doctrine query to accept an array of values to search on a field. I need them to be case insensitive matches so I'm using like clauses, otherwise I could just use in which would make things much simpler. What I want to end up with is a query like like:

"SELECT * FROM tableName t WHERE (t.option LIKE "option1" OR t.option LIKE "option2" OR t.option LIKE "option3"); 

So I tried the following:

function getItems( $options = array() ) {

    $qb = $this->_em->createQueryBuilder();
    $qb->from('tableName', 't')
        ->select('t');

        $conditions = $qb->expr()->orX();
        foreach ($options as $option) {
            $conditions->add($qb->expr()->like('option', $option));
        }
        $qb->andWhere($conditions);
    }

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

getItems( array('option1','option2','option3') );

But the values don't get escaped so you end up with a query like the below which throws an error:

SELECT * FROM tableName t WHERE (t.option LIKE option1 OR t.option LIKE option2 OR t.option LIKE option3)

This is normally where you would use named parameters like:

$qb->expr()->like('option', ':option');
$qb->setParameter( 'option', $option );

But you can't set the same parameter name multiple times with an array of values. I'm probably missing something obvious, bit of a novice with doctrine. Any ideas?

1
  • First, you can use ->where(' A LIKE "B" '), second, you can escape your $option in the foreach before passing to like(). Commented Nov 20, 2015 at 7:12

1 Answer 1

1

You should be using the literal expression:

$conditions->add($qb->expr()->like('option', $qb->expr()->literal($option)));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.