0

I'm a student and, for my final project, I need to make a searchtool.

I know how to search if a string is contained in my database but I want to search with an array now. So I do it and that's work... but only if it's exactly what it's in my array, not if it's contained.

So my Repository function is like this

public function findByMots($value)
    {
        return $this->createQueryBuilder('a')
            ->andWhere('a.titre IN (:val) OR a.contenu IN (:val) OR t.theme IN (:val)')
            ->setParameter('val', $value)
            ->leftJoin('App\Entity\Theme', 't', 'WITH', 't.id_article = a.id')
            ->orderBy('a.id', 'DESC')
            ->getQuery()
            ->getResult()
        ;
    }

My value is an array with string in, but if one string is "raccoon" he doesn't find my article who has a title like "I love raccoon". Does anybody know please?


I found a method!

public function findByMots($value)
    {
        $search =  $this->createQueryBuilder('a')
            ->leftJoin('App\Entity\Theme', 't', 'WITH', 't.id_article = a.id');
        $number = 0;
        foreach ($value as $valu) {
            $search = $search->orWhere('a.titre LIKE :val' . $number . ' OR a.contenu LIKE :val' . $number . ' OR t.theme LIKE :val' . $number . '')
                ->setParameter('val'.$number, '%'.$valu.'%');

            $number++;
        }
        $search = $search
            ->orderBy('a.id', 'DESC')
            ->getQuery()
            ->getResult();

        return $search;
    }
  • 1
    Does [this](https://stackoverflow.com/questions/31243022/doctrine-dbal-setparameter-with-array-value) help? – Bossman Mar 01 '22 at 15:03
  • 1
    Or [this](https://stackoverflow.com/questions/2602252/mysql-query-string-contains)? – S. Dre Mar 01 '22 at 15:04
  • As already mentioned, you need to use `WHERE LIKE %search_term%` syntax. BUT with doctrine it's kinda "special" `->andWhere('a.title LIKE :val')->setParameter('val', '%' . $value . '%')` - yes! You have to concatenate `"%"` with your $value. Just `->andWhere('a.title LIKE %:val%')` - **won't work** – V-Light Mar 01 '22 at 22:00
  • Yup, but that's doesn't work with an array in $value. With string it's perfect, but whit array that's transform my array into a string :/ – Grégor Ecorce Mar 02 '22 at 08:14

0 Answers0