0

I'm trying to figure out how to correctly iterate on an array in a symfony 5 repository custom query.

I explain myself. App user may check several values on a page. I want to display objects that matches all (but not necessarily only) the checked values.

I easily catch an array of the values that I send to a controller with ajax but I encounter issues with my custom query.

Values matches the "label" parameter of a table (Tag) which is related (ManyToMany) to the table (Flash) I select with my query.

So far, I tried a lot of things, like :

public function getFlashesByTagsList($tags)
    {
        $qb = $this->createQueryBuilder('f');
        $andX = $qb->expr()->andX();
        $qb->join('f.tags', 't');
        $qb->addSelect('t');
        foreach($tags as $tag) {
            $andX->add(
                $qb->expr()->like('t.label', ':tag'),
                $qb->setParameter(':tag', '%'.$tag.'%')
            );
        }
        $qb->add('where', $andX);
        $qb->orderBy('f.id', 'DESC');
        $result = $qb->getQuery()->getResult();
        return $result;
    }

But nothing I tried worked. If only one value is sent, I get all the objects that has this value in their tags but as soon as there are more, it only get me the ones that matches the last one in the $tags array.

ovb
  • 1
  • 1
  • `setParameter` does not belong inside the `$andX->add()`. Your issue is because the placeholder name `':tag'` is overridden on each iteration, causing your resulting query to be `tag = $tag`. You would need to append an index for each tag to be accounted for: `$ph = 'tag_' . $i++;` `$qb->andWhere($qb->expr()->like('t.label', ':' . $ph)); $qb->setParameter($ph, '%'.$tag.'%');` – Will B. Nov 21 '21 at 05:03
  • Thank you ! I didn't think about the override. it works now. – ovb Nov 22 '21 at 10:40

0 Answers0