Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine and Symfony2: WHERE a.title LIKE $array

Hey I'm writing this post because I have few problem passing an array value in the doctrine query.

Here is the entire query as it is:

$data = $request->request->all();
$dql   = "SELECT a FROM PfBlogBundle:Article a WHERE a.title LIKE '{$data['search']}' ORDER by a.id DESC";

If I print_r($data) I get the value so it's there somewhere. I just don't understand why it's not passing in the query.. Was expecting LIKE '{$data['search']}' to work but it doesn't.

like image 354
daneczech Avatar asked Sep 05 '13 10:09

daneczech


1 Answers

From what I can tell by your snippet, you're looking for something like this:

$entityManager->getRepository('PfBlogBundle:Article')
              ->findBy(
                   array(
                      'key' => 'value'
                   )
               );

Where key is the property/field and the value is the value to look for. Check the Symfony manual page. The bit you're after is Fetching Objects from the Database.
To use a like in the where clause, refer to this SO question, on how to use setParameter. You'll get your query with this:

$repo = $entityManager->getRepository('PfBlogBundle:Article');
$query = $repo->createQueryBuilder('a')
               ->where('a.title LIKE :title')
               ->setParameter('title', '%'.$data['search'].'%')
               ->getQuery();

Of course, add wildcards to suite your needs. I've enclosed the $data['search'] value in two % wildcards, which is slow, but then again: I don't know what you're actually doing. It might be that all you're after is the case-insensitive nature of LIKE, in which case the % can be left out all together...

Based on your previous questions (BTW: consider accepting an answer once in a while):

public function searchAction(Request $request)
{
    $data = $request->get->all();
    $repo = $this->getDoctrine()
                  ->getRepository('PfBlogBundle:Article');
    $query = $repo->createQueryBuilder('a')
                   ->where('a.title LIKE :title')
                   ->setParameter('title', '%'.$data['search'].'%')
                   ->getQuery();
    $paginator  = $this->get('knp_paginator');
    $pagination = $paginator->paginate(
        $query->getResults(),//get the results here
        $this->requrest->get('page',1),
        4
    );
    return $this->render('PfBlogBundle:Default:blog.html.twig', array('pagination'=>$pagination));
}

But this is just a crude fix, Google doctrine-symfony pagination, there are many detailed blog-posts on the matter

like image 105
Elias Van Ootegem Avatar answered Oct 06 '22 11:10

Elias Van Ootegem