如何在Symfony2中使用一个LIKE数据库查询

问题描述:

请我需要知道什么是问题,它应该工作,但它没有得到结果。如何在Symfony2中使用一个LIKE数据库查询

有我的控制器:

public function searchAction() 
{ 
    $form = $this->createForm(new SearchCoursesType()); 
    $request = $this->getRequest(); 
    if($request->getMethod() == 'POST') 
    { 
     $form->bind($request); 
     if($form->isValid()) 
     { 
      $em = $this->getDoctrine()->getManager(); 
      $data = $this->getRequest()->request->get('formation_appbundle_scourse'); 
      $courses = $em->getRepository('FormationAppBundle:Course')->findCoursesByParametres($data); 
      return $this->render('FormationAppBundle:Courses:coursesList.html.twig', array('courses' => $courses)); 
     } 
    } 
    return $this->render('FormationAppBundle:Template:searchIndex.html.twig', array('form' => $form->createView())); 
} 

我用一个简单的表格

{{ form_start(form) }} 
    {{ form_widget(form) }} 
<input type="submit" value="Create" /> 
{{ form_end(form) }} 

我觉得这没”在库中定义的搜索功能,这样

public function findCoursesByParametres($data) 

{ 

    $query = $this->createQueryBuilder('a'); 

    $query->where($query->expr()->like('a.title', ':title')) 

     ->setParameters(array(

      'title' => $data['title'] 
     )); 
    return $query->getQuery()->getResult(); 

} 

t收集输入,但我找不到问题

+0

$数据= $形式 - >的getData();应该得到你的头衔。但没有一些%字符的情况下使用LIKE没有什么意义。 – Cerad

改变你的函数库:

public function findCoursesByParametres($data) 
{ 
    $query = $this->createQueryBuilder('a') 
       ->where('a.title LIKE :title') 
       ->setParameters(array(
        'title' => '%' . $data['title'] . '%' 
      )); 
    return $query->getQuery()->getResult(); 
    }