简体   繁体   中英

Doctrine and Like query symfony2

I have a search bar in my page and the action in my in charge of looking for what the user search for is this :

 public function searchAction(Request $request){

        $em = $this->container->get('doctrine')->getEntityManager();

        $evenements= $em->getRepository('Mql14mqlmeBundle:Evenement')->findAll();
        if ('POST' === $request->getMethod()) {

            $search = $request->get('search');
    $query = $this->container->get('doctrine')->getEntityManager()->createQuery( 'SELECT e FROM Mql14mqlmeBundle:Evenement e WHERE e.nom LIKE :search') 
             ->setParameter('search', $search);
        $resultats = $query->getResult();



        return $this->container->get('templating')->renderResponse('Mql14mqlmeBundle:Event:search.html.twig', array(
            'resultats'=>$resultats,

        ));

        }
   return $this->listerAction();
        }

It's working if the user put the exact name of some event in the database, but I want to make the search possible even if it's only a part of the name, I tried this in the query:

    $query = $this->container->get('doctrine')->getEntityManager()->createQuery( 'SELECT e FROM Mql14mqlmeBundle:Evenement e WHERE e.nom LIKE :%search%') 
               ->setParameter('search', $search);

But I'm getting this error: Invalid parameter format, : given, but :name or ?num expected.

Try to change parameter like this:

$query = $this
    ->container
    ->get('doctrine')
    ->getEntityManager()
    ->createQuery(
        'SELECT e FROM Mql14mqlmeBundle:Evenement e WHERE e.nom LIKE :search'
    ) 
    ->setParameter('search', '%'.$search.'%');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM