Search code examples
phplaraveldoctrinesql-like

PHP Doctrine2 search "Like" with an Array "%$array%"


Doctrine2.5 With PHP 5.6

I have an array of things to search, example: in a table of user, i want to search for the names of everyone that have the name "Reis" or "Shimidt" in the field name. With the array

$arraySearch = ['Reis', 'Shimidt'];

I want to bring for example the following entries,

  • John Reis Carlson,
  • Mary Shimidt Lincoln,
  • Bill Reis Abdonor Gates.

I tried something like this:

$this->query->andWhere(" pb.name LIKE '%:name%' ");
$this->query->setParameter('name', $name, \Doctrine\DBAL\Types\Type::SIMPLE_ARRAY);

It doesnt work, i also tried like this, but obviously returned array to string conversion:

$this->query->setParameter('name', '%'.$name.'%', \Doctrine\DBAL\Types\Type::SIMPLE_ARRAY);

Any ideas how to solution this, without to do a messy code ?


Solution

  • I advise you to use something like this:

    foreach ($arraySearch as $search) {
        $this->query->orWhere(" pb.name LIKE :search ");
        $this->query->setParameter("search", '%'.$search.'%');
    }