Home > Mobile >  Find the result if the field text contains specific string
Find the result if the field text contains specific string

Time:08-03

I am working on a symfony(4.4) project. I am trying to a make query with doctrine to match all results that the text contains any of the strings defined in the array.

The array of the words is:

$keywords = [
'test',
'test2',
'test3'
];

The query that I'm trying to do this is:

$qb = $this->createQueryBuilder('of');
foreach ($keywords as $key => $keyword) {
    $qb
        ->orWhere('of.text LIKE :keyword'.$key)
        ->setParameter('keyword'.$key, '%'.$keyword.'%');
}

When I execute the query I get error:

[Syntax Error] line 0, col 7: Error: Expected IdentificationVariable | ScalarExpression | AggregateExpression | FunctionDeclaration | PartialObjectExpression | "(" Subselect ")" | CaseExpression, got 'of'

I'am using orWhere, because i need to match any of these values, not all (that's why I don't use the andWhere). What I'm missing ?

CodePudding user response:

I think there is a syntax error (ie 'of.text LIKE:keyword'.$key). And maybe 'of' is a reserved keyword (https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#quoting-reserved-words).

You can try:

$qb = $this->createQueryBuilder('`of`');
foreach ($keywords as $keyword) {
    $qb->orWhere('of.text LIKE :searchTerm')
    $qb->setParameter('searchTerm', '%'.$keyword.'%');
}

CodePudding user response:

The following code will help you to get the result as you want: 
There is no need to produce unique parameter names. 
So I have used only one parameter 'keyword' in the query.

$keywords = ['test','test2','test3'];
$qb = $this->createQueryBuilder('q');
foreach ($keywords as $key => $keyword) {
    $client->orWhere('q.text LIKE :keyword')
        ->setParameter('keyword', '%'.$keyword.'%');
    }
  • Related