Khqlil
Khqlil

Reputation: 85

I have probleme in query builder SYMFONY

I want to search an user by "firstname" and "lastname"

so at first i have an input text where i put the lastname and firstname in the same input

and second i have created this query

public function findListByName($name)
{
    return $this->createQueryBuilder('c')
        ->where('c.firstname LIKE :name')
        ->orWhere('c.lastname LIKE :name)
        ->setParameter('name', '%'.$name.'%')
        ->getQuery()
        ->getResult();
}

updated with :

return $this->createQueryBuilder('c')
        ->where('c.firstname LIKE :name1')
        ->orWhere('c.lastname LIKE :name2')
        ->setParameter(':name1', '%'.$name.'%')
        ->setParameter('name2', '%'.$name.'%')
        ->getQuery()
        ->getResult();

Now for example : i have in Data base the firstname = "test" and lastname="test2"

and if i put in input this word:"test" or "test2" its work and return the user

if i put the word: "test test2" is not work(no results)

so who have a solution to solve this problem please

Upvotes: 2

Views: 56

Answers (2)

A.Marwan
A.Marwan

Reputation: 76

you can check if $name have space

$qb = $this->createQueryBuilder('c')
$isMultiple = false;
        if (strpos($name, ' ')) {
            $isMultiple = true;
            $name = explode(' ', $name);
        }
        if ($isMultiple) {
            $qb->andWhere('c.firstname LIKE :firstname')
                ->andWhere('c.lastname LIKE :lastname')
                ->setParameters('firstname', '%'.$name[0].'%')
                ->setParameters('lastname', '%'.$name[1].'%');
        } else {
            $qb->andWhere('c.firstname LIKE :name')
                ->orWhere('c.lastname LIKE :name')
                ->setParameters('name', '%'.$name.'%');
        }

Upvotes: 0

ScaisEdge
ScaisEdge

Reputation: 133360

Could be because You are using two times a param so try assign assign two param

eg: try this way

public function findListByName($name)
{
      return $this->createQueryBuilder('c')
        ->where('c.firstname LIKE concat('%',:name1', '%') )
        ->orWhere('c.lastname LIKE concat('%',:name2', '%') )
        ->orWhere('concat(c.firstname,' ',c.lastname) LIKE concat('%',:name3', '%') )
        ->setParameters(array('name1'=> $name, 'name2' =>$name, 'name3'=>$name)
        ->getQuery()
        ->getResult();
}

Upvotes: 1

Related Questions