我想用symfony为我的网站制作搜索功能。 我做了这样的表格:
<div class="input-group" id="adv-search">
{{ form_start(form) }}
{{ form_widget(form.searchText,{'attr':{'id':'search_box','class':'search_box form-control ','placeholder':'Search'}}) }}
<div class="input-group-btn">
<div class="btn-group" role="group">
<button type="button" id="search_button" class="btn btn-search"><span
class="glyphicon glyphicon-search"
aria-hidden="true"></span></button>
</div>
</div>
{{ form_end(form) }}
</div>
接下来我得到用户写的内容:
if ($form->isSubmitted()) {
$data = $form->getData();
$string = $data['searchText'];
echo '<pre>';
\Doctrine\Common\Util\Debug::dump($string);
exit;
echo '</pre>';
}
在我接受用户编写的内容之后,我想在表格行中搜索该文本并返回一个数组以便在twig中显示它。 我正在考虑创建一个查询构建器,进行选择,但它没有用。
$this->getEntityManager()->createQuery('SELECT u FROM ParkResortBundle:Ad u
WHERE u. LIKE :string OR u.lastname LIKE :string')
->setParameter('string','%'.$string.'%')
->getResult();
}
答案 0 :(得分:0)
查看您的查询:
...
你在哪里。 LIKE
...
我认为你错过了专栏名称
答案 1 :(得分:0)
您可能需要在搜索控制器中使用Orx
Expression
尝试在搜索控制器中添加use语句。
use Doctrine\ORM\Query\Expr\Orx;
然后您的查询构建器应该与createQueryBuilder
不同,而不是createQuery
。
$qb = $this->getDoctrine()->getEntityManager()->getRepository( 'ParkResortBundle:Ad' )->createQueryBuilder( 'p' );
$qb->add( 'where',
$qb->expr()->orX(
$qb->expr()->like( 'p.firstname', "'%{$SearchKeyword}%'" ),
$qb->expr()->like( 'p.lastname', "'%{$SearchKeyword}%'" )
)
);
$searchResult = $qb->getQuery()->getResult();
编辑1:
将 OrderBy 与查询构建器一起使用:
$qb = $this->getDoctrine()->getEntityManager()->getRepository( 'ParkResortBundle:Ad' )->createQueryBuilder( 'p' );
$qb->add( 'where',
$qb->expr()->orX(
$qb->expr()->like( 'p.firstname', "'%{$SearchKeyword}%'" ),
$qb->expr()->like( 'p.lastname', "'%{$SearchKeyword}%'" )
)
);
$qb->add('orderBy', 'p.firstname ASC');
$searchResult = $qb->getQuery()->getResult();
以下是QueryBuilder中可用的辅助方法的完整列表: