Domanda

I have two entities: Image and Tags, with a many-to-many relationship.

Image has some fields: code, description, author and tags which implements the many-to-many relationship.

Tag has just two fields: name and images.

I'm building a very general search form, with just an input field where you can write any text and then it will be returned any Image that has that text in its code, description or author fields, or in any of its tags name field.

For the non-relation fields it's easy. I have in my controller (query is just de GET parameter used for the search):

$em = $this->getDoctrine()->getManager();

$qb = $em->getRepository('MyBundle:Image')->createQueryBuilder('i');

$qb
->where(
      $qb->expr()->like('i.code', $qb->expr()->literal('%'.$request->get('query').'%'))
      )
->orWhere(
      $qb->expr()->like('i.description', $qb->expr()->literal('%'.$request->get('query').'%'))
      )
->orWhere(
      $qb->expr()->like('i.author', $qb->expr()->literal('%'.$request->get('query').'%'))
      );

Now, I don't know how to proceed for the each name field of the tags.

I had tried to use a virtual field in the Image entity that returned all the tags as a string, but I can't use it later in the query builder.

Thanks a lot!

È stato utile?

Soluzione

SELECT i FROM YourBundle:Image i
LEFT JOIN i.tags t
WHERE i.code LIKE :q OR i.desc LIKE :q OR i.author LIKE :q OR t.name LIKE :q

This should work.

With qb:

$qb->leftJoin('i.tags', 't')
   ->where($qb->expr()->like('t.name', $qb->expr()->literal('%' . $query . '%')));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top