1

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!

Waiting for Dev...
  • 12,629
  • 5
  • 47
  • 57

1 Answers1

2
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 . '%')));
nikita2206
  • 1,129
  • 2
  • 10
  • 17
  • +1. Thanks for your answer. That way works. But I would preffer to use the query builder instead of DQL. I think a good ORM should encourage working in an Object Oriented way. I will set your answer as the correct if nobody else proposes an alternative with the query builder. – Waiting for Dev... Nov 03 '12 at 12:48
  • I detect a problem with it. Using that way, images without tags are not considered when searching. – Waiting for Dev... Nov 03 '12 at 13:10
  • 1
    There should be LEFT JOIN then. – nikita2206 Nov 03 '12 at 13:23