在symfony2中进行搜索

时间:2014-02-07 13:36:11

标签: php symfony search

    public function searchAction(Request $request)  
{    
    $em = $this->getDoctrine()->getEntityManager();
    $searchName = $request->query->get('search_name');
    $searches= \explode(' ', $searchName); 
    $search = $em->createQueryBuilder()->select('c')
                    ->from('SavvyContactBundle:Contact',  'c')
                    ->where("c.name = :name")
                    ->setParameter('name', $searchName )
                    ->addOrderBy('c.id', 'DESC')
                    ->getQuery(); 

    return $this->render('SavvyContactBundle:Contact:list.html.twig', array('search' => $search, 'searches' => $searches));
}

这是对特定单词的基本搜索,我想像搜索在输入字段中输入的每个单词一样进行预先搜索,所以如果我在某处错了,请帮忙告诉我。

1 个答案:

答案 0 :(得分:0)

我是用手机写的,但你明白了吗?

...

$words = explode(' ', $searchName);

$qb = $em->createQueryBuilder()
    ->select('c')
    ->from('SavvyContactBundle:Contact', 'c')
    ->addOrderBy('c.id', 'DESC');

foreach ($words as $word) {

    $qb
        ->orWhere("c.name = :word")
        ->setParameter('word', $word);
}

$contacts = $qb->getQuery()->execute();

...